0% found this document useful (0 votes)
2 views31 pages

Java Unit 1

Java is a high-level, platform-independent programming language developed by Sun Microsystems in 1995, known for its object-oriented features and security. It has three editions: Java Standard Edition (JSE), Java Enterprise Edition (JEE), and Java Micro Edition (JME), each catering to different application needs. Key concepts include OOP principles, data types, variables, and the Java Virtual Machine (JVM) which allows Java programs to run on any platform.

Uploaded by

garimarwt.2412
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views31 pages

Java Unit 1

Java is a high-level, platform-independent programming language developed by Sun Microsystems in 1995, known for its object-oriented features and security. It has three editions: Java Standard Edition (JSE), Java Enterprise Edition (JEE), and Java Micro Edition (JME), each catering to different application needs. Key concepts include OOP principles, data types, variables, and the Java Virtual Machine (JVM) which allows Java programs to run on any platform.

Uploaded by

garimarwt.2412
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA Programming

Foundations of Java
• Java is a Programming Language and a Platform Independent. Java is a high level, robust,
object oriented and secure programming language.
• Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his team changed the name from Oak
to Java.
• Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.
Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
• Java Standard Edition (JSE): It is used to create programs for a desk top computer.
• Java Enterprise Edition (JEE): It is used to create large programs that run on the server
and manages heavy traffic and complex transactions.
• Java Micro Edition (JME): It is used to develop applications for small devices such as set-
top boxes, phone, and appliances.
Types of Java Applications
There are four types of Java applications that can be created using Java programming:
• Standalone Applications: Java standalone applications use GUI components such as AWT,
Swing, and Java FX. These components contain buttons, list, menu, scroll panel, etc. It is
also known as desktop alienations.
• Enterprise Applications: An application which is distributed in nature is called enterprise
applications.
• Web Applications: An application that run on the server is called web applications. We
use JSP, Servlet, Spring, and Hibernate technologies for creating web applications.
• Mobile Applications: Java ME is a cross-platform to develop mobile applications which
run across smart phones. Java is a platform for App Development in Android.
Features of Java:
• Object Oriented – Java implements basic concepts of Object-oriented programming System
(OOPS) i.e. Object, Class, Inheritance, Polymorphism, Abstraction, Encapsulation. In Java,
everything is an Object. Java can be easily extended since it is based on the Object model.
• Platform Independent − Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by the
Virtual Machine (JVM) on whichever platform it is being run on.
• Simple – Java fallows the basic Syntax of C, C++. If you understand the basic concept of OOPS
then it is easy to master in java.
• Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
• Architecture-neutral − Java compiler generates an architecture-neutral object file format,
which makes the compiled code executable on many processors, with the presence of Java
runtime system.
• Portable − Being architecture-neutral and having no implementation dependent aspects of
the specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
• Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
• Multithreaded − With Java's multithreaded feature In java we can write programs that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
• Interpreted − Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.
• High Performance − With the use of Just-In-Time compilers, Java enables high performance.
• Distributed − Java is designed for the distributed environment of the internet.
• Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt
to an evolving environment. Java programs can carry extensive amount of run-time information
that can be used to verify and resolve accesses to objects on run-time.

OOP Concepts
Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming
paradigm where everything is represented as an object is known as truly object-oriented
programming language.
Smalltalk is considered as the first truly object-oriented programming language.
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
1. Class
2. Object
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message Passing
1. Class
A Class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. Using classes, you
can create multiple objects with the same behavior instead of writing their code multiple times.
In general, class declarations can include these components in order:
• Modifiers: A class can be public or have default access
• Class name: The class name should begin with the initial letter capitalized by convention.
• Body: The class body is surrounded by braces, {}.
2. Object
An Object is a basic unit of Object-Oriented Programming that represents real-life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods.
The objects are what perform your code, they are the part of your code visible to the
viewer/user.

3. Abstraction
Abstraction in Java is the process of hiding implementation details and showing only the
essential features of an object. It helps users focus on what an object does rather than how it
does it.
4. Encapsulation
Encapsulation is the process of wrapping data and methods into a single unit, usually a class,
and restricting direct access to the data. It acts as a protective shield that prevents data from
being accessed directly from outside the class.
5. Inheritance
Inheritance is a core OOP concept in Java that allows one class to acquire the fields and
methods of another class using the extends keyword. It represents an “is-a” relationship
between classes.
• The class being inherited is called the superclass, and the inheriting class is the subclass.
• A subclass can use existing features of the superclass and also add its own.
• Inheritance promotes code reusability and reduces redundancy.

6. Polymorphism
Polymorphism means “many forms”, where a single entity can behave differently in different
situations. In Java, it allows the same method or object to show different behavior based on
context.
• Same method, different behavior depending on the object
• Achieved through method overloading and method overriding
7. Dynamic Binding
Dynamic Binding (also known as Late Binding or Run-time Binding) occurs when the Java Virtual
Machine (JVM) determines which specific method implementation to execute at runtime rather
than at compile time.
8. Message Passing
Message Passing is the process by which objects communicate with one another. In Java, this is
simply the act of one object calling a method of another object to request an action or
information.

JVM
The Java Virtual Machine (JVM) is a core component of the Java Runtime Environment (JRE)
that allows Java programs to run on any platform without modification. JVM acts as an
interpreter between Java bytecode and the underlying hardware, providing Java’s famous Write
Once, Run Anywhere (WORA) capability.
• Java source (.java) -> compiled by javac -> bytecode (.class)
• JVM loads the bytecode, verifies it, links it, and then executes it
• Execution may involve interpreting bytecode or using Just-In-Time (JIT) compilation to
convert “hot” code into native machine code for performance
• Garbage collection runs in the background to reclaim memory from unused objects
Simple Java Program
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Code Explanation
A Java program follows a specific structure where every piece of code must reside inside a
class
• public class HelloWorld:
o public is an access modifier that makes the class accessible from anywhere.
o class is a keyword used to define a new class.
o HelloWorld is the name of the class, which must exactly match the filename (e.g.,
[Link]).
• public static void main(String[] args):
o This is the entry point of the program where the Java Virtual Machine (JVM) starts
execution.
o static means the method belongs to the class and can be called without creating an
object of the class.
o void indicates that this method does not return any value.
o String[] args is a parameter that allows the program to accept command-line
arguments as an array of strings
• [Link]("Hello, World!");:
o This statement prints the text inside the quotation marks to the screen.
o The semicolon (;) at the end is mandatory for every statement in Java to signal the
end of a command.

Command Line Arguments in Java


Command-line arguments in Java allow users to pass input parameters to a program during
execution via the terminal or command prompt. These arguments are essential for making a
program dynamic, as they enable external inputs without modifying the source code. They
are stored as an array of String values using the main method and can be accessed using
indexing.
Syntax of Command-Line Arguments in Java
To pass command-line arguments to a Java program, follow this syntax:
java YourProgramClassName arg1 arg2 arg3 ...

• YourProgramClassName: The Java class that contains the main method.


• arg1, arg2, arg3: The command-line arguments passed to the program, separated by
spaces.
Example
Here's a simple Java program demonstrating what is command line arguments in Java
and how they are used:
public class CommandLineExample {
public static void main(String[] args) {
[Link]("Command-line arguments are: ");
for (String arg : args) {
[Link](arg);
}
}
}

If executed with:
java CommandLineExample Hello World 123

Output
Command-line arguments are:
Hello
World
123
JAVA – DATA TYPES
Data type is used to allocate sufficient memory space for the data. Data types
specify the different sizes and values that can be stored in the variable.
➢ Java is a strongly Typed Language.
➢ Definition: strongly Typed Language:
Java is a strongly typed programming language because every variable must be declared
with a data type. A variable cannot start off life without knowing the range of values it can
hold, and once it is declared, the data type of the variable cannot change.

Data types in Java are of two types:


1. Primitive data types (Intrinsic or built-in types ) :- : The primitive data types
include boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types (Derived or Reference Types): The non-primitive
data types include Classes, Interfaces, Strings and Arrays.

1. Primitive Types:
Primitive data types are those whose variables allow us to store only one value and
never allow storing multiple values of same type. This is a data type whose variable
can hold maximum one value at a time.
There are eight primitive types in Java:
Integer Types:
1. int
2. short
3. long
4. byte

Floating-point Types:
5. float
6. double

Others:
7. char
8. Boolean

➢ Integer Types:
The integer types are form numbers without fractional parts. Negative values are
[Link] provides the four integer types shown below:
Storage Default
Type Range Example
Requirement Value
-2,147,483,648(-2^31)
int a = 100000,
int 4 bytes to 0
int b = -200000
2,147,483,647 (2^31-1)
short s = 10000,
short 2 bytes -32,768 (-2^15) to 32,767 (2^15-1) 0
short r = -20000
-9,223,372,036,854,775,808 (-2^63)
long a = 100000L,
long 8 bytes to 0L
int b = -200000L
9,223,372,036,854,775,808 (2^63-1)
byte a = 100 ,
byte 1 byte -128 (-2^7) to 127 (2^7-1) byte b = -50 0

➢ Floating-point Types:
The floating-point types denote numbers with fractional parts. The
two floating-pointtypes are shown below:
Storage Default
Type Requirement Range Example Value
Approximately ±3.40282347E+38F
float 4 bytes (6-7 significant decimal digits) float f1 =234.5f 0.0f

Approximately
double d1 =
double 8 bytes ±1.79769313486231570E+308 123.4 0.0d
(15 significant decimal digits)

➢ char:
• char data type is a single 16-bit Unicode character.
• Minimum value is '\u0000' (or 0).
• Maximum value is '\uffff' (or 65,535 inclusive).
• Char data type is used to store any character.
• Example: char letterA ='A'

➢ boolean:
• boolean data type represents one bit of information.
• There are only two possible values: true and false.
• This data type is used for simple flags that track true/false conditions.
• Default value is false.
• Example: boolean one = true

2. Derived Types (Reference Types):


• Derived data types are those whose variables allow us to store multiple
values of same type. But they never allow storing multiple values of
different types.
• A reference variable can be used to refer to any object of the declared type or any
compatible type.
• These are the data type whose variable can hold more than one value of similar
type.
• The value of a reference type variable, in contrast to that of a primitive type,
is a reference to (an address of) the value or set of values represented by
the variable.
• Example
int a[] = {10,20,30}; // valid
int b[] = {100, 'A', "ABC"}; // invalid
Animal animal = new Animal("giraffe"); //Object

JAVA – VARIABLES

➢ A Variable is a named piece of memory that is used for storing data in java
Program.
➢ A variable is an identifier used for storing a data value.
➢ A Variable may take different values at different times during the execution
if the program, unlike the constants.
➢ The variable's type determines what values it can hold and what
operations can beperformed on it.
➢ Syntax to declare variables:
datatype identifier [=value][,identifier [ =value] …];

➢ Example of Variable names:


int average=0.0, height, total height;

➢ Rules followed for variable names ( consist of alphabets, digits,


underscore anddollar characters)
1. A variable name must begin with a letter and must be a sequence of letter or
digits.
2. They must not begin with digits.
3. Uppercase and lowercase variables are not the same.
a. Example: Total and total are two variables which are distinct.
4. It should not be a keyword.
5. Whitespace is not allowed.
6. Variable names can be of any length.

➢ Initializing Variables:
✓ After the declaration of a variable, it must be initialized by means of assignment
statement.
✓ It is not possible to use the values of uninitialized variables.
✓ Two ways to initialize a variable:
1. Initialize after declaration:
Syntax: variablename=value;

int months;
months=1;

2. Declare and initialize on the same line:

Syntax: Datatype variablename=value;

int months=12;
➢ Dynamic Initialization of a Variable:
Java allows variables to be initialized dynamically using any valid expression at thetime
the variable is declared.

Example: Program that computes the remainder of the division operation:

class FindRemainer
{
public static void main(String arg[]) {int num=5,den=2;
int rem=num%den; [Link](“Remainder is “ rem);
}
}

Output:
Remainder is 1

In the above program there are three variables num, den and rem. num and den are
initialized by constants whereas rem is initialized dynamically by the modulo division
operation on num and den.

JAVA - VARIABLE TYPES


There are three kinds of variables in Java:
1. Local variables
2. Instance variables
3. Class/static variables
Local Variables Instance Variable Class / Static Variables
Class variables also known as
static variables are declared
with the static keyword in a
Instance variables are class, but outside a method,
Local variables aredeclared in
declared in a class, but constructor or a block.
methods, constructors, or
outside a method, There would only be one copy
blocks.
constructor or any block. of each class variable per
class, regardless of how many
objects are created from it.

Local variables are created


Instance variables are created
when the method, Static variables are created
when an object is created with
constructor or block is when the program starts and
the use of the keyword 'new'
entered and the variable will destroyed when the program
and destroyed when the
be destroyed once it exits the stops.
object is destroyed.
method, constructor or block.

Access modifiers cannot be Access modifiers can be used Access modifiers can be
used for local variables. forinstance variables. used for class variables.

Local variables are visible The instance variables are


only within the declared visible for all methods, Visibility is similar to
method, constructor or constructors and block in the instance variables.
block. class.
Instance variables have
default values. For numbers
There is no default value for
the default value is 0, for
local variables so local
Booleans it is false and for Default values are same as
variables should be declared
object references it is null. instance variables.
and an initial value should be
Values can be assigned during
assigned before the first use.
the declaration or within the
constructor.
Instance variables can be
accesseddirectly by calling the
variable name inside the class.
Static variables can be
Local variables can only be However within static
accessed by calling with the
access inside the declared methods and different class
class name.
block. should be called using the fully
[Link].
qualified name as follows:
[Link]
me.

Example program illustrating the use of all the above variables:

class area
{
int length=20;
int breadth=30;
static int classvar=2500;
void calc()
{
int areas=length*breadth;
[Link](“The area is “+areas+” [Link]”);
}

public static void main(String args[])


{
area a=new area();
[Link]();
[Link](“Static Variable Value : “+classvar);
}
}
Output:
The area is 600 [Link]
Static Variable Value : 2500

Program Explanation:
Class name: area
Method names: calc() and main()
Local variables: areas (accessed only in the particular method)
Instance variables: length and breadth (accessed only through the object‘s method)
Static variable: accessed anywhere in the program, without object reference

ARRAYS
Definition:
An array is a collection of similar type of elements which has contiguous
memory location.
Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements. We can store only a fixed set of
elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Advantage of Array:
• Code Optimization: It makes the code optimized; we can retrieve or sort the data
easily.
• Random access: We can get any data located at any index position.

Disadvantage of Array:
• Size Limit: We can store only fixed size of elements in the array. It doesn't growits
size at runtime.

Types of Array:
There are two types of array.
1. One-Dimensional Arrays
2. Multidimensional Arrays

1. One-Dimensional Array:

Definition: One-dimensional array is an array in which the elements are stored


in onevariable name by using only one subscript.

➢ Creating an array:
Three steps to create an array:
1. Declaration of the array
2. Instantiation of the array
3. Initialization of arrays

1. Declaration of the array:


Declaration of array means the specification of array variable, data_type and
array_name.
Syntax to Declare an Array in java:
dataType[] arrayRefVar; (or)
dataType []arrayRefVar; (or)
dataType arrayRefVar[];

Example:
int[] floppy; (or) int []floppy (or) int floppy[];

2. Instantiation of the array:

Definition:
Allocating memory spaces for the declared array in memory (RAM) is called as
Instantiation of an array.

Syntax:
arrayRefVar=new datatype[size];

Example: floppy=new int[10];

3. Initialization of arrays:Definition:
Storing the values in the array element is called as Initialization of arrays.

Syntax to initialize values to array element:


arrayRefVar[index value]=constant or value;

Example:
floppy[0]=20;

SHORTHAND TO CREATE AN ARRAY OBJECT:


Java has shorthand to create an array object and supply initial values at the
same timewhen it is created.
dataType[] arrayRefVar={list of values};
(or)
dataType []arrayRefVar={list of values};
(or)
dataType arrayRefVar[]={list of values};
(or)
dataType arrayRefVar[]=arrayVariable;

Example 1:
int regno[]={101,102,103,104,105,106};
int reg[]=regno;

Example 2: double[] myList = new double[10];

ARRAY LENGTH:
The variable length can identify the length of array in Java. To find the number of
elements of an array, use [Link].
Example1:
int regno[10]; len1=[Link];
Example 2:
for(int i=0;i<[Link];i++)
[Link](regno[i]);

Following picture represents array myList. Here, myList holds ten double values and
the indicesare from 0 to 9.

Example: (One-Dimensional Array)

class Array
{
public static void main(String[] args)
{
int month_days[];
month_days=new int[12];
month_days[0]=31;
month_days[1]=28;
month_days[2]=31;
month_days[3]=30;
month_days[4]=31;
month_days[5]=30;
month_days[6]=31;
month_days[7]=31;
month_days[8]=30;
month_days[9]=31;
month_days[10]=30;
month_days[11]=31;

[Link](“April has ”+month_days[3]+ “ days.”);


}
}
Output:

April has 30 days.


Example 2: Finding sum of the array elements and maximum from the array:

public class TestArray


{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (double element: myList)
{
[Link](element);
}

// Summing all elementsdouble total = 0;


for (int i = 0; i < [Link]; i++)
{
total += myList[i];
}
[Link]("Total is " + total);

// Finding the largest elementdouble

max = myList[0];
for (int i = 1; i < [Link]; i++)
{
if (myList[i] > max)
max = myList[i];
}
[Link]("Max is " + max);
}
}

Output:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

2. Multidimensional Arrays:

Definition:
Multidimensional arrays are arrays of arrays. It is an array which uses more than
one index to access array elements. In multidimensional arrays, data is stored in
row and column based index (also known as matrix form).

Uses of Multidimensional Arrays:


✓ Used for table
✓ Used for more complex arrangements
Syntax to Declare Multidimensional Array in java:

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java:

int[][] arr=new int[3][3]; //3 row and 3 column - internally this matrix is implemented as arrays of arrays of int.

Example to initialize Multidimensional Array in java:

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Examples to declare, instantiate, initialize and print the 2Dimensional array:

class twoDarray
{
public static void main(String args[])
{
int array1[][]=new int[4][5];// declares an 2D array.
int array2[][]={{1,2,3},{2,4,5},{4,4,5}}; //declaring and initializing 2D arrayint i,j,k=0;

// Storing and printing the values of Array1

[Link]("-------Array 1-------- " );


for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
array1[i][j]=k;k++;
[Link](array1[i][j]+ " ");
}
[Link]();
}

// printing 2D array2
[Link]("-------Array 2--------");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
[Link](array2[i][j]+
}
[Link]();
}
}
}
Output:
-------------Array1------------
01234
56789
10 11 12 13 14
15 16 17 18 19

-------------Array2------------
123
245
445

In the above program, the statement int array1[][]=new int[4][5]; is interpreted


automatically as follows:
array1[0]=new int[5];array1[1]=new int[5];array1[2]=new int[5];array1[3]=new int[5];

It means that, when we allocate memory for a multidimensional array, we need to only
specify the memory for the first (leftmost) dimension. We can allocate the remaining
dimensions separately with different sizes.

Example: Manually allocate differing size second dimensions:

class twoDarray
{
public static void main(String args[])
{
int array1[][]=new int[4][]; // declares an 2D array.

array1[0]=new int[1];
array1[1]=new int[2];
array1[2]=new int[3];
array1[3]=new int[4];
int i,j,k=0;

// Storing and printing the values of Array


for(i=0;i<4;i++)
{
for(j=0;j<i+1;j++)
{
array1[i][j]=k;k++;
[Link](array1[i][j]+ " ");
}
[Link]();
}
}
}

Output:
0
12
345
6789
OPERATORS
Operators are used to manipulate primitive data types.
Java operators can be classified as unary,binary, or ternary—meaning taking one, two,
or three arguments, respectively.

Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to perform
various operations
i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and –

1. class OperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x=10;
6. [Link](x++); //10 (11)
7. [Link](++x); //12
8. [Link](x--); //12 (11)
9. [Link](--x); //108.
10.}
11.}

Output:
10
12
12
10

Java Unary Operator Example 2: ++ and –

1. class OperatorExample
2. {
3. public static void main(String args[])
4. {
5. int a=10;
6. int b=10;
7. [Link](a++ + ++a); //10+12=22
8. [Link](b++ + b++); //10+11=21 7.
9. }
10. }
Output:
22
21

Java Unary Operator Example: ~ and !


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. [Link](~a); //-11 (minus of total positive value which starts from 0)
8. [Link](~b); //9 (positive of total minus, positive starts from 0)
9. [Link](!c); //false (opposite of boolean value)
10. [Link](!d); //true
11. }
12. }

Output:
-11
9
False
true
A binary or ternary operator appears between its arguments.

Java operators fall into eight different categories:

1. Assignment
2. Arithmetic
3. Relational
4. Logical
5. Bitwise
6. Compound assignment
7. Conditional
8. Type
Assignment Operators =
Arithmetic Operators - + * / % ++ --
Relational Operators > < >= <= == !=
Logical Operators && || & | ! ^
Bit wise Operator & | ^ >> >>>
Compound Assignment += -= *= /= %=
Operators <<= >>= >>>=
Conditional Operator ?:

1. Java Assignment Operator

The java assignment operator statement has the following syntax:


<variable> = <expression>

If the value already exists in the variable it is overwritten by the assignment operator
(=).

Java Assignment Operator Example


1. class OperatorExample{
2. public static void main(String args[])
3. {
4. int a=10;
5. int b=20;
6. a+=4; //a=a+4 (a=10+4)
7. b-=4; //b=b-4 (b=20-4)
8. [Link](a);
9. [Link](b);
10. }
11. }
Output:

14
16

2. Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction, multiplication,
and [Link] act as basic mathematical operations.

Assume integer variable A holds 10 and variable B holds 20, then:


Operator Description Example
A + B will give
+ Addition - Adds values on either side of the operator
30
Subtraction - Subtracts right hand operand from left hand A - B will give
- operand -10
A * B will give
* Multiplication - Multiplies values on either side of the operator 200
/ Division - Divides left hand operand by right hand operand B / A will give 2
Modulus - Divides left hand operand by right hand operand B % A will give
%
and returns remainder 0
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19

Java Arithmetic Operator Example: Expression


1. class OperatorExample
2. {
3. public static void main(String args[])
4. {
5. [Link](10*10/5+3-1*4/2);
6. }
7. }

Output:
21
3. Relational Operators
Relational operators in Java are used to compare 2 or more objects. Java provides six
relational operators: Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example
Checks if the values of two operands are equal or not, if yes (A == B) is not
== then condition becomes true. true.

Checks if the values of two operands are equal or not, ifvalues


!= (A != B) is true.
are not equal then condition becomes true.

Checks if the value of left operand is greater than the value of (A > B) is not
> right operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than the value ofright
< operand, if yes then condition becomes true. (A < B) is true.

Checks if the value of left operand is greater than or equal tothe (A >= B) is not
>= value of right operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than or equal tothe


<= value of right operand, if yes then condition becomestrue. (A <= B) is true.
Example:

public RelationalOperatorsDemo( )
{
int x = 10, y = 5;
[Link]("x > y : "+(x > y));
[Link]("x < y : "+(x < y));
[Link]("x >= y : "+(x >= y));
[Link]("x <= y : "+(x <= y));
[Link]("x == y : "+(x == y));
[Link]("x != y : "+(x != y));

public static void main(String args[])


{
new RelationalOperatorsDemo();
}
}

Output:
$java RelationalOperatorsDemo
x > y : true
x < y : false
x >= y : true
x <= y : false
x == y : false
x != y : true

4. Logical Operators

Logical operators return a true or false value based on the state of the Variables. Given
that x and y represent boolean expressions, the boolean logical operators are defined
in the Table below.

x&y x|y
X Y !x x && y x || y x^y
True True Fals true true False
e
True False Fals false true True
e
False True True false true True
False False True false false false

Example:
public class LogicalOperatorsDemo
{
public LogicalOperatorsDemo()

{
boolean x = true;
boolean y = false;
[Link]("x & y : " + (x & y));
[Link]("x && y : " + (x && y));
[Link]("x | y : " + (x | y));
[Link]("x || y: " + (x || y));
[Link]("x ^ y : " + (x ^ y));
[Link]("!x : " + (!x));
}
public static void main(String args[])
{
new LogicalOperatorsDemo();
}
}
Output:
$java LogicalOperatorsDemo
x & y : false
x && y : false
x | y : true
x || y: true
x ^ y : true
!x : false
5. Bitwise Operators

Java provides Bit wise operators to manipulate the contents of variables at the bit level.
The result of applying bitwise operators between two corresponding bits in the
operandsis shown in the Table below.

A B ~A A&B A|B A^B

1 1 0 1 1 0

1 0 0 0 1 1

0 1 1 0 1 1

0 0 1 0 0 0

public class Test


{
public static void main(String args[])
{
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */int c = 0;
c = a & b; /* 12 = 0000 1100 */
[Link]("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */

[Link]("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
[Link]("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
[Link]("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
[Link]("a << 2 = " + c );
c = a >> 2; /* 215 = 1111 */
[Link]("a >> 2 = " + c );
c = a >>> 2; /* 215 = 0000 1111 */
[Link]("a >>> 2 = " + c );
}
}

Output:
$java Test

a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15

6. Compound Assignment operators

The compound operators perform shortcuts in common programming operations.


Java has eleven compound assignment operators.

Syntax: argument1 operator = argument2.

Java Assignment Operator Example


1. class OperatorExample
2. {
3. public static void main(String[] args)
4. {
5. int a=10;
6. a+=3; //10+3
7. [Link](a);
8. a-=4; //13-4
9. [Link](a);
10. a*=2; //9*2
11. [Link](a);
12. a/=2; //18/2

13. [Link](a);12.
14. }
15. }

Output:
13
9
18
9

7. Conditional Operators

The Conditional operator is the only ternary (operator takes three arguments)
operator in Java. The operator evaluates the first argument and, if true, evaluates the
second argument.

If the first argument evaluates to false, then the third argument is evaluated. The
conditional operator is the expression equivalent of the if-else statement.

The conditional expression can be nested and the conditional operator associates from
right to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)

Example:

public class TernaryOperatorsDemo {

public TernaryOperatorsDemo() {
int x = 10, y = 12, z = 0;
z = x > y ? x : y;
[Link]("z : " + z);

public static void main(String args[]) {


new TernaryOperatorsDemo();

Output:
$java TernaryOperatorsDemo
z : 12
8. instanceof Operator:

This operator is used only for object reference variables. The operator checks whether
the object is of a particular type(class type or interface type). instanceof operator is
written as:

(Object reference variable ) instanceof (class/interface type)


If the object referred by the variable on the left side of the operator passes the IS-A
check for the class/interface type on the right side, then the result will be true.
Following is the

Example:
public class Test
{
public static void main(String args[])
{
String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
[Link]( result );
}
}

This would produce the following result:


True

OPERATOR PRECEDENCE:
The order in which operators are applied is known as precedence. Operators with a higher
precedence are applied before operators with a lower precedence.

The operator precedence order of Java is shown below. Operators at the top of the table
are applied before operators lower down in the table.

If two operators have the same precedence, they are applied in the order they appear in a
statement. That is, from left to right. You can use parentheses to override the default
precedence.

Category Operator Associativity


Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

Example:

In an operation such as,


result = 4 + 5 * 3

First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19.
Note that ‗*‘ takes higher precedence than ‗+‘ according to chart shown above. This kindof
precedence of one operator over another applies to all the operators.

You might also like