Operators (Autosaved)
Operators (Autosaved)
++a; //11
Ex:
public class Ex2
{
public static void main(String[] args)
{
int x=10;
int y=20;
int z=++x+y++;
int a=++x+x++;
int b=++y+x++;
System.out.println(z);
System.out.println(a);
System.out.println(b);
}
}
Output:
31
24
35
Post Increment:
The value of the operand is incremented but the previous value is
retained temporarily until the execution of this statement and it gets
updated before the execution of the next statement.
a++; // 11
Arithmetic Operators
The Java programming language provides operators that perform
addition, subtraction, multiplication, and division.
The only symbol that might look new to you is "%", which divides one
operand by another and returns the remainder as its result.
Operator Use Description
+ op1 + op2 Adds op1 and op2; also used to concatenate strings
Left shift(<<)
Unsigned shift(>>>)
Right shift(>>):
Shifts the bits of the number to the right and fills 0 on voids left as a
result.
The leftmost bit depends on the sign of initial number. Similar effect as of
dividing the number with some power of two.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
Left shift(<<):
Shifts the bits of the number to the left and fills 0 on voids left as a
result.
Ex: int a=10;
System.out.println(a<<1);
Output:20
int a=10;
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0
Bitwise Operators:
0 0 0
0 1 0
1 0 0
1 1 1
Ex:
1101 //13
&
1100 //12
------------------
1100 //12
Inclusive or means that if either of the two bits is 1, the result is 1. The
following table shows the results of an inclusive or operation.
0 0 0
0 1 1
1 0 1
1 1 1
Exclusive or means that if the two operand bits are different the result
is 1; otherwise the result is 0.
The following table shows the results of an exclusive or operation.
Ex:
int x = 8; if (x < 9)
{
// do something
}
Operator Use Description
Returns true if op1 is greater
> op1 > op2
than op2
Returns true if op1 is greater than or
>= op1 >= op2
equal to op2
< op1 < op2 Returns true if op1 is less than op2
Returns true if op1 is less than or
<= op1 <= op2
equal to op2
Returns true if op1 and op2 are
== op1 == op2
equal
Returns true if op1 and op2 are not
!= op1 != op2
equal
Logical operators:
Operator Use Description
Returns true if
|| op1 || op2
either op1 or op2 is true;
conditionally evaluates op2
Ternary operators:
The conditional operator is a ternary operator (it has three operands)
Syntax:
x = (boolean expression) ? value to assign if true : value to assign if false
Ex:
int i=10;
String s = (i<4)?“A":(i>50)?“B":“C";
System.out.println(s);
Assignment Operators.
The basic assignment operator looks as follows and assigns the value
of op2 to op1.
op1 = op2;
Shortcut Assignment Operators