Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

Operators


Operators are used along with operands to perform operations.. Or we can say in simple words that an operator is a symbol which is basically used to perform an operation.

Types of Operators

1. Arithmetic Operator
2. Assignment Operator
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Ternary Operator (Conditional Operator)
7. Increment/Decrement Operator
8. New Operator
9. Instance Operator

1. Arithmetic Operator

• Arithmetic Operators provide operations that perform addition, subtraction, multiplication, division and modulus.
• Arithmetic Operators are the binary operators which require two operands. The result of arithmetic operations depends upon type of operand used.
• Operands must be in Number Format.

            
public class Arithmetic_Operator {
    public static void main (String[] args) {
    int a = 100;
    byte b = 20;

    System.out.println(a + b);
    System.out.println(a - b);
    System.out.println(a * b);
    System.out.println(a/b);
    System.out.println(a % b);

    }
}
        
    120
    80
    2000
    5
    0
            


Here, we are define a class with name as ArithmeticOperator having main method that performs Arithmetic Operations.

            
public class Arithmetic_Operator {

	public static void main(String[] args) {
		int a = 100;
		boolean b1 = true;

		System.out.println(a + b1);
		System.out.println(a - b1);
		System.out.println(a * b1);
		System.out.println(a / b1);
		System.out.println(a % b1);

	}

}
            
    Test1.java:7: error: bad operand types for binary operator '+'
        System.out.println(a + b1);
                             ^
    first type:  int
    second type: boolean
    Test1.java:8: error: bad operand types for binary operator '-'
                    System.out.println(a - b1);
                                        ^
    first type:  int
    second type: boolean
    Test1.java:9: error: bad operand types for binary operator '*'
                    System.out.println(a * b1);
                                        ^
    first type:  int
    second type: boolean
    Test1.java:10: error: bad operand types for binary operator '/'
                    System.out.println(a / b1);
                                        ^
    first type:  int
    second type: boolean
    Test1.java:11: error: bad operand types for binary operator '%'
                    System.out.println(a % b1);
                                        ^
    first type:  int
    second type: boolean
    5 errors
    error: compilation failed
            


Here, we define one class with name Arithmetic_Operator. Inside this class we perform arithmetic operation along with a boolean operand. We get an error because arithmetic operation cannot be performed with a boolean value.

2. Assignment Operator (=)

it is used to assign some value to a corresponding variable. Which means it stores the Right-hand side value into the Left hand side variable. The left hand side variable can be called destination and the right hand side variable can be called source.

Syntax:
   Destination = source

Assignment operators can work in the following three ways:

Case 1: Destination = source [comparing the basis of Data Type]
Case 2: Destination > source
Case 3: Destination < source

Case 1: Destination = Source

            
public class Assignment_Operator {

  public static void main(String[] args) {

	// Case: 1 [Destination = Source]
	
int a = 10;
	int b = a; // Destination[b] [int] | source[a] [int]
	System.out.println(b);
	
	}
}

            
        
    10
            


Type Casting

Type casting is the process of converting one type of value into the compatible data types. byte, short, int, long, float, double, char are compatible to each other, so we can perform typecasting between them.

Types of Type Casting:

• Implicit Type Casting
• Explicit Type Casting

Implicit Type Casting

• It is introduced in jdk 1.5
• JVM performs Implicit Type Casting when the destination is Greater than the source which means
  Destination > Source

            
public class Assignment_Operator {

  public static void main(String[] args) {

	// Case:2 [Destination > Source]

	byte b1 = 10;
	short s1 = b1; // Destination[s1] [short] | source[b1] [byte]
	System.out.println(s1);

		
	}

}
            
        
    10
            


In the above Image we have the binary representation of byte type of variable on 8-bits which is b1 and their value is 10.



And When we are trying to assign byte type of value into thea short type of variable then JVM performs an implicit type casting and converts the byte type of value into short type which we can see intoas the 16-bits representation.

Explicit Type Casting

Sometimes we need to perform Type Casting explicitly, generally it can be done when Destination < Source, however this can cause Data Loss .

            
public class Arithmetic_Operator {

    public static void main(String[] args) {

        short s2=260;
        byte b2=(byte) s2; // Destination[b2] [byte] | source[s2] [s]
    System.out.println(b2);
 
    }

}
            
        
    4
            


In the above image we have binary representation of short type of variable s2 on 16-bits and their value is 260.


When we try to store short type of data into the byte type of variable which is b2, we need to type- cast short type of value into the byte- type i.e. here we will need to type-cast 16-bits data into 8-bits. and wWe can see here that we are not able to store 8-bits from left side into byte type of variable b2, this situation is called Data Loss.

3. Relational Operators

Relational Operators are used to establish the relation between two expressions or it can be said that by using this relation operator we can form a relational expression. The result of relational expression always returns some Boolean values, that is either true or false.

            
public class Relational_Operator {

public static void main(String[] args) {
    int a = 20;
    int b = 10;
    System.out.println(a > b);
    System.out.println(a < b);
    System.out.println(a >= b);
    System.out.println(a <= b);
    System.out.println(a == b);
    System.out.println(a != b);

}

}
        
        
    true
    false
    true
    false
    false
    true
            


            
public class Relational_Operator1 {

public static void main(String[] args) {
    boolean a = false;
    boolean b = true;
    System.out.println(a > b);
    System.out.println(a < b);
    System.out.println(a >= b);
    System.out.println(a <= b);
    System.out.println(a == b);
    System.out.println(a != b);

    }
}
            
        
    Test1.java:6: error: bad operand types for binary operator '>'
        System.out.println(a > b);
                             ^
    first type:  boolean
    second type: boolean
    Test1.java:7: error: bad operand types for binary operator '<'
                    System.out.println(a < b);
                                        ^
    first type:  boolean
    second type: boolean
    Test1.java:8: error: bad operand types for binary operator '>='
                    System.out.println(a >= b);
                                        ^
    first type:  boolean
    second type: boolean
    Test1.java:9: error: bad operand types for binary operator '<='
                    System.out.println(a <= b);
                                        ^
    first type:  boolean
    second type: boolean
    4 errors
    error: compilation failed
            

Here, we when we defining one class as Relational_Operator1 and inside the class if we declare two Boolean type variables a and b, we get some error when we compare them. This is shown in the above Output.



4. Logical Operators

The && and || operators perform Logical-AND and Logical-OR operations on two boolean expressions.

These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

Different types of Logical Operator:

&& Logical - AND
|| Logical – OR
! Logical - NOT

&& Logical - AND

Logical And (&&) operator works on a truth table which we have mentioned bellow and we use logical AND operator to evaluate more than one required condition.

            
public class Logical_Operators1 {

public static void main(String[] args) {
    System.out.println(true && false);
    System.out.println(false && true);
    System.out.println(true && true);
    System.out.println(false && false);
}
}

            
                
    false
    false
    true
    false
            
            
public class Logical_Operators1 {

public static void main(String[] args) {

    byte age = 10;
    System.out.println(age >= 18 && age <= 27);

       
       int a = 10;
    System.out.println(a < 0 && a++ == 56);
    System.out.println(a);
    
    
    int a1 = 10;
    System.out.println(a1 > 0 && a1++ == 56);
    System.out.println(a1);

}

}

            
        
    false
    false
    10
    false
    11
            


In the above code we have a variable age and the value is 10 and age must be in between 18 and 27. In the other session of code we have an int type of variable a with value as 10. Here we check 2 conditions a < 0 and a++ == 25 along with logical AND (&&) operator.Since from first condition (a < 0) we get false condition hence the control does not move to evaluate the second condition (a++ == 25), also prost-increment (a++) operation does not process and we get 10 as the value of a. In the last section of the program we have an int type of variable which is a1 and its value is 10 and we check 2 conditions a1 > 0 and a1++ == 56 along with logical AND (&&) operator, because from the first condition (a1 > 0) we are get a true condition hence the control moves to evaluate the second condition (a1++ == 56) and prost-increment (a++) operation now processes and we are get 11 as the value of a1.

|| Logical – OR

Logical OR (||) operator works on a truth table like Logical AND (&&) which we have mentioned bellow and we use logical OR operator to evaluate more than one optional condition.

            
public class Logical_OR_Operator {

public static void main(String[] args) {
    System.out.println(true || true);
    System.out.println(true || false);
    System.out.println(false || true);
    System.out.println(false || false);


       int a = 10;
    System.out.println(a > 0 || a++ != 20);
    System.out.println(a);
    
    int a1 = 10;
    System.out.println(a1 < 0 || a1++ != 20);
    System.out.println(a1);

    }

}

            
        
    true
    true
    true
    false
    true
    10
    true
    11
            


In the above code we are preforming Logical OR (||) operation on the basis of their Truth Table. In the other session of code we have an int type of variable a and the value is 10 and we are checking 2 conditions a > 0 and a++ != 20 along with logical OR (||) operator, because from first condition (a > 0) we geta true condition hence the control does not move to evaluate the second condition (a++ != 20) and prost-increment (a++) operation does not process and we are get 10 as the value of a. In the last section of the program we have an int type of variable which is a1 and the value is 10 and we are checking 2 conditions a1 <0 and a1++ != 20 along with logical OR (&&) operator, because from first condition (a1 < 0) we are getting false condition hence the control now moves to evaluate the second condition (a1++ != 20) and prost-increment (a++) operation now processes and we are get 11 as the value of a1.

! Logical - NOT

It is a Unary Operator and it also works on Truth Table which we have mentioned below.

            
public class Logical_NOT_Operators {

public static void main(String[] args) {
int account = 0, pancard = 1, passport = 1; // 1-> available | 0-> not available

System.out.println(!(!(account == 1 && (pancard == 1 || passport == 1))));

    }
}                  
    false
            


In this code we have three int type of variable accounts:, pancard and passport their values are 0, 1, 1 respectively. Here 1 and 0 values are representing the status of user document availability: 1 represents that the document is available and 0 represents that the document is not available. ¬¬¬ Thereafter we check three conditions (account == 1 && (pan card == 1 || passport == 1)) which represents a logic account is a required document and user must possess one or more document, either a pan card or a passport. In the current values if we get false output then we can apply Logical Not (!) operator on the result twice. The first Logical Not Operator converts the false result into true then the second Logical NOT (!) operator converts true again into false and hence we get false as the final output.


5. Bitwise Operators

Bitwise Operator is used to work on individual bits which means it performs the operation on a bit.

1. Bitwise AND Operator [ &]
2. Bitwise OR Operator [ | ]
3. Bitwise XOR Operator [ ^ ]
4. Left-Shift Operator [ << ]
5. Right-Shift Operator [ >> ]
6. Negation or Tilde Operator [ ~ ]

Bitwise AND Operator [ &]

• It is a binary operator and is denoted by ‘&’.
• It performs operations bit by bit and if both bits are 1 then only it returns 1, otherwise it returns 0.

            
public class Bitwise_AND_Operator {

public static void main(String[] args) {
    int number1 = 12;
    int number2 = 25;
    int result;

    // bitwise AND between 12 and 25
    result = number1 & number2;
    System.out.println(result);
    }

}

            
        
    8
            

Here, we take two integer values 12 and 25 and convert into binary, the use of Bitwise AND Operator has been shown.

12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise AND Operation of 12 and 25
00001100 = 12 (In Decimal)
00011001 = 25 (In Decimal)
____________
00001000 = 8 (In Decimal)

Bitwise OR Operator [ | ]

It is a binary operator and it’s denoted by ‘|’.
It performs operations bit by bit and if both bits are 0 then only it returns 0,¬¬ otherwise it returns 1.

            
public class Bitwise_OR_Operator {

public static void main(String[] args) {
    int number1 = 5;
    int number2 = 7;
    int result;

    // bitwise OR between 5 and 7
    result = number1 | number2;
    System.out.println(result); 
}

}
            
        
    7
            

Here we have taken two integer values 5 and 7 and we convert these into binary, Bitwise OR Operator has been used.

a = 5 = 00000101 (In Binary)
b = 7 = 00000111 (In Binary)

Bitwise OR Operation of 5 and 7
00000101
00000111
________
 00000111 = 7 (In decimal)

Bitwise XOR Operator [ ^ ]

• It is a binary operator and it's denoted by ^ .
• It is also called caret operator.
• It returns 0 if both bits are the same, otherwise it returns 1.

            
public class Bitwise_XOR_Operator {

public static void main(String[] args) {
    int number1 = 5;
    int number2 = 7;
    int result;

    // bitwise XOR between 5 and 7
    result = number1 ^ number2;
    System.out.println(result);

    }

}

            
        
    2
            

Here, we take two integer values 5 and 7 and convert into binary, we make use of Bitwise XOR Operator

a = 5 = 00000101 (In Binary)
b = 7 = 00000111 (In Binary)

Bitwise XOR Operation of 5 and 7
00000101
00000111
________
 00000010 = 2 (In decimal)

Left-Shift Operator [ << ]

• The bits in the left operand are shifted to the left by the number of places specified in the right operand.
• It is denoted by the symbol <<

            
public class Left_Shift_Operator {

public static void main(String[] args) {
    int a = 10;
    System.out.println(a << 1);

    }

}
            
        
    20
            

Here, we have an int type of variable which is a and the value is 10. In the above diagram we have 32-bit binary representation of int a = 10 then we shift ‘a’ towards left hand side by 1.

Signed Right-shift Operator [ >> ]

• The Signed Right-Shift operator shifts bits towards Right side with specified numbers of bit.
• It’s denoted by symbol >> .
• In the case of negative(-) numbers the left significant bit occupied by 1 and in positive(+) numbers left significant bit occupied by 0.

            
class Signed_Right_Shift_Operator{

   public static void main(String[] args) {
    	int a = -10;
		System.out.println("-10 :-      "+Integer.toBinaryString(a));
     	int res1 = (a >> 1);
		System.out.println("-10 >> 1 :- "+Integer.toBinaryString(res1));
		int b = 10;
		System.out.println("10 :-      "+Integer.toBinaryString(b));
     	int res2 = (b >> 1);
		System.out.println("10 >> 1 :- "+Integer.toBinaryString(res2));
   }

}
        
    -10 :-      11111111111111111111111111110110
    -10 >> 1 :- 11111111111111111111111111111011
    10 :-      1010
    10 >> 1 :- 101
            

In the above image we have 32-bit representation of -10 and we are trying to shift the bits towards Right side and because it is a negative value so as we can see the left significant bit is occupied by 1

In the above image we have 32-bit representation of 10 and we are trying to shift the bits towards Right side and because it is a positive value so as we can see the left significant bit is occupied by 0

Unsigned Right-shift Operator [ >>> ]

• Unsigned right shift operator is exactly similar to SIGNED RIGHT SHIFT operator except that the vacant left-most bits are replaced with 0 either the number is positive or negative.
• It is denoted by symbol >>>

            
class Unsigned_Right_Shift_Operator{

   public static void main(String[] args) {
    	int a = -10;
		System.out.println("-10 :-      "+Integer.toBinaryString(a));
     	int res1 = (a >>> 1);
		System.out.println("-10 >>> 1 :- "+Integer.toBinaryString(res1));
		int b = 10;
		System.out.println("10 :-      "+Integer.toBinaryString(b));
     	int res2 = (b >>> 1);
		System.out.println("10 >>> 1 :- "+Integer.toBinaryString(res2));
   }

}
            
        
    -10 :-      11111111111111111111111111110110
    -10 >>> 1 :- 1111111111111111111111111111011
    10 :-      1010
    10 >>> 1 :- 101
            

In the above image we have 32-bit representation of -10 and we are trying to shift the bits towards Right side and because it is a negative value so as we can see the left significant bit is occupied by 0.

In the above image we have 32-bit representation of 10 and we are trying to shift the bits towards Right side and because it is a negative value so as we can see the left significant bit is occupied by 0.

Negation or Tilde Operator [ ~ ]

• The bitwise complement operator is a unary operator. It is denoted by ~.
• It performs Negation operation on the given operand.

            
public class Tilde_Operator {

public static void main(String[] args) {
    byte b1 = 17;
    System.out.println(~b1); 

}
}
            
        
    -18
            

In the above code we have a byte type of variable b1 and the value is 17 and we are getting -18 as the result of Negation operation, here it becomes necessary to know that how Negation (~) operation works. First we need to convert given operand in binary. In the above example we have byte b1 = 17 and their binary conversation on 8-bits is 00010001, after binary conversion we calculate their 1’s compliment as 11101110 and then we need to calculate the sum of 1’s bit position which is 128+64+32+8+4+2 = 238, then we subtract 238 from 256 (max-bit of 8-bit representation) i.e. 238 – 256 and get -18 as the result

6. Ternary Operator (Conditional Operator)

• In Java ternary operator is the conditional operator that takes three operands.
• It is a conditional operator that provides a shorter syntax for the if..else statement.

Syntax:
condition ? trueStatement : falseStatement

Condition: First part is the condition section.
TrueStatement: Second is the code block which executes if first part of condition is true.
FalseStatement: The Third part code block executes if condition is false.

            
public class Ternary_Operator {

    public static void main(String[] args) {

    System.out.println("------without ternary operator-----");
        int number1 = 20;
        int number2 = 10;
    String result = (number1 < number2) ? "number1 is greater than number2" : "number1 is less than or equal to number2";
    System.out.println(result);

}
}

            
        
    ------without ternary operator-----
    number1 is less than or equal to number2      
            

In the above code, we have two int types of variables: number1 and number2- and their values are 20 and 10 respectively. Here we are checking a condition number1 > number2 because we are getting true from the condition, so control moves to true section and assigns “number1 is greater than number2” in result and we are get the same output.

7. Increment/Decrement Operator

Increment and Decrement operator is used to increase or decrease the value of operand by 1.

Increment operator (++):
The increment operator is an operator which is used to increase the value of an operand by 1.

Types of increment Operator

Pre-increment operator (++x)
post-increment operator (x++)

1. pre increment operator(++x)

If we use pre-increment operator then first the value of operand is increased by 1 before the performance of any other operation (that have been mentioned above).

            
public class Pre_Increment_Operator {

public static void main(String[] args) {
    int x = 10;
    int y = ++x;
    System.out.println("y value is: " + y);
    
    int a = 20;
    System.out.println(++a == 20);

}

}

            
        
    y value is: 11
    false
            

In the above program we have an int type of variable x and its value is 10 and we are performing an operation (int y = ++x). Since we have used pre-increment operation the value of x increases by 1 first and then when assigned into thevariable y, the value of y will be 11. Similarly, in (++a == 20), first a will be 21, and thereafter when we t compare we get a false.

2. Post increment operator(x++)

If we use post-increment operator then it performs the specified operation first and thereafter it increases the value of the operand by 1.

            
public class Post_Increment_Operator {

public static void main(String[] args) {
    int x = 10;
    int y = x++;
    System.out.println("y value is: " + y);
    System.out.println(“x value is: ”+ x);


}

}

            
        
    y value is: 10
    x value is: 11
            

In the above program we have an int type of variable x and its value is 10. Here we are performing an operation (int y = x++). Since we have used post-increment operation, it assigns the value of x into the y first. We get the value of y as 10 and thereafter the operator increases the value of x by 1.

Decrement Operator (--):

Decrement Operator is basically used to decrease the value of operand by 1.

Types of Decrement Operator

Pre decrement (--x)
Post decrement (x--)

1. Pre decrement (--x)

If we use the pre-decrement operator first it decreases the value of operand by 1 and thereafter only it performs the specified operation.

            
public class Pre_Decrement_Operator {

public static void main(String[] args) {
    int x = 10;
    int y = --x;
    System.out.println("y value is: " + y);

}

}
            
        
    y value is: 9
            

In the above program we have an int type of variable x and its value is 10 and we are performing an operation (int y = --x).Since we have used pre-decrement operation, it decreases the value of x by 1 then the operator assignes this decremented value into y and we get value of y as 9.

2. Post decrement (x--)

If we use post decrement operator then first of all the specified operation is performed and thereafter the operator decreases the value of operand by 1.

            
public class Post_Dcrement_Operator {

    public static void main(String[] args) {
        int x = 10;
        int y = x--;
        System.out.println("y value is: " + y);

    }

}

            
        
    y value is: 10
            

In the above program we have an int type of variable x and its value is 10 and we are performing an operation (int y = x--). Since we have used post-decrement operator, first the value of x (as 10) is assigned into y and then the operator decreases the value of the operand by 1.

8. new Operator

In Java new is a keyword, which we use for allocating memory into Heap dynamically for an object of a class.

Object creation with new keyword.

In the above image we have j1 which is a reference variable of Jtc Type. j1 is allocated 8-bytes memory. New Jtc() is an Object of Jtc class.In new Jtc(), new is a keyword which is dedicated to dynamic memory allocation in Heap for specified object, alsoJtc() is a constructor invocation of Jtc class. Finally reference of Object [new Jtc()] stores into j1.

            
class Jtc {
	public Jtc() {
		System.out.println("Welcome to Jtc");
	}

	void display() {
		System.out.println("display() method in Jtc");
	}
}

public class New_Operator_Example {

	public static void main(String[] args) {
		Jtc j1 = new Jtc();
		j1.display();

	}

}
            
        
    Welcome to Jtc
    display() method in Jtc
            

In the above program we have 2 different classes Jtc and New_Operaotor_Example.Jtc class is having a constructor and one method which is display() and New_Operator_Example class is having main() in which we are creating an object Jtc j1 = new Jtc() and along with the object we are invoking display() method of Jtc class.

9. instanceof operator

instanceof is a keyword in Java which is used to check whether an object is an instance of a specified type or not. Here the result is always a boolean type of value.

Note:
In order to apply instanceof operator between two different types of objects there must be a super and sub relation between them.

            
public class Jtc_Example{

public static void main(String[] args) {
    JtcSuper j1 = new JtcSuper();
    
    System.out.println(j1 instanceof JtcSuper); // true
    System.out.println(j1 instanceof JtcSub); // false

JtcSub j2 = new JtcSub();

    System.out.println(j2 instanceof JtcSuper); // true
    System.out.println(j2 instanceof JtcSub); // true

}

}
class JtcSuper {}

class JtcSub extends JtcSuper {}

            
        
    true
    false
    true
    true
            

In the above code we can see JtcSub class is a child class of JtcSuper class and in Jtc_Example class we are creating an object of JtcSuper class (JtcSuper j1 = new JtcSuper()) and we are trying to check whether j1 is an instance of JtcSuper class or not and we are getting true as the result. Thereafter we are checking whether j1 is an instance of JtcSub class or not and we are getting false as the result. In the other section we have an Object of JtcSub class (JtsSub j2 = new JtcSub()) and we are checking the same condition for JtcSuper and JtcSub class and in both cases we are getting true as the result, because as we know that super class object contains all the information of their sub class as well.