Operators
Operators
Operators
• Introduction
• Assignment Operator
• Arithmetic Operator
• Relational Operator
• Bitwise Operator
• Conditional Operator
• Type Comparison Operator
• Unary Operator
Introduction
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Compound Assignments
Arithmetic operators are combined with the simple
assignment operator to create compound assignments.
== equal to
!= not equal to
• If we use the || and && forms, rather than the | and & forms
of these operators, Java will not bother to evaluate the right-
hand operand when the outcome of the expression can be
determined by the left operand alone.
This is very useful when the right-hand operand depends
on the value of the left one in order to function properly.
For example
if (denom != 0 && num / denom > 10)
• If denom does not equal zero, then the expression after the colon
is evaluated and used for the value of the entire ? expression.
•
The Left Shift Operator
• The left shift operator,<<, shifts all of the bits in a value to
the left a specified number of times.
value << num
• Example:
01000001 65 << 2
00000100 4
The Right Shift Operator
• The right shift operator, >>, shifts all of the bits in a value
to the right a specified number of times.
value >> num
• It is also known as signed right shift.
• Example:
00100011 35 >> 2
00001000 8
• When we are shifting right, the top (leftmost) bits exposed
by the right shift are filled in with the previous contents of
the top bit.
• Example:
– 11111111 11111111 11111111 11111111 –1 in
binary as an int
– >>>24
– 00000000 00000000 00000000 11111111 255 in
binary as an int
Operator Precedence
Highest
() [] .
++ -- %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= Op=
Lowest
Brainstorming 1
What will be the output of the following code snippets?
System.out.println(34>>3);
System.out.println(-34>>3);
System.out.println(-34>>>3);
Brainstorming 2
int x = 10, y = 5;
while(x- - > 7 || + + y < 8 );
System.out.print(x);
System.out.print(y);
A. 95
B. 67
C. 78
D. 48
E. 77
F. N.O.T
Brainstorming 3
System.out.print(2>1||4>3?false:true);
class X{}
class Y extends X{}
class Z extends Y{}
X x1 = new Y();
Y y1 = new Z();
Y y2 = new Y();
System.out.println( x1 instanceof X);
System.out.println( x1 instanceof Z);
System.out.println( y1 instanceof Z);
System.out.println( y2 instanceof X);
Brainstorming 4
System.out.print(2>1||4>3?false:true);