3 Operators
3 Operators
Operators in java
Assignment assignment = += -= *= /= %=
Java Unary Operator
class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++); 10
System.out.println(++x); 12
12
System.out.println(x--);
System.out.println(--x); 10
}}
SHIFT OPERATOR
Shift Operator
• Left shift operator shifts all bits towards the left by a certain number of
specified bits.
• It is denoted by <<.
Java Left Shift Operator Example
class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}}
Right Shift Operator
• Right shift operator shifts all bits towards the right by a certain number of
specified bits.
• It is denoted by >>.
• When we shift any number to the right, the least significant bits (rightmost) are
discarded and the most significant position (leftmost) is filled with the sign bit.
Java Right Shift Operator Example
class OperatorExample{
public static void main(String args[]){
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}}
Relation operators
Relation operators
> Check if operand on the left is greater than operand on the right
int a, b;
a=40;
b=30;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
Bitwise operators
Bitwise operators
class Main {
public static void main(String[] args) {
class Main {
public static void main(String[] args) {
class Main {
public static void main(String[] args) {
For example,
• Consider an integer 35.
• As per the rule, the bitwise complement of 35 should be -(35 + 1) = -36.
Program
class Main {
public static void main(String[] args) {
// bitwise complement of 35
result = ~number;
System.out.println(result); // prints -36
}
}
Logical Operators
Logical operators
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Java Ternary Operator
System.out.println(result);