Java Operators and its 8 Types that you should know about!

Now as you are familiar with the declaration and initialization of variables in Java, you might be eager to know how to perform with them. In this tutorial, we will learn the various operators in Java which we can further use accordingly for our need/purpose.

In computer programming, an operator is a special symbol that is used to perform operations on the variables and values. The operators represent the operations (specific tasks) and the objects/variables of the operations are known as operands.

Types of Operators in Java

Java comes with a rich set of operators, which comprises of many kinds of operators such as arithmetic, relational, and logical and many other types of operators. Let us discuss each of them in detail.

1. Arithmetic Operators in Java

Arithmetic operators are used to perform mathematical expressions or arithmetic calculations in the same way we use them in algebra.

Java provides operators for five basic arithmetic calculations: addition, subtraction, multiplication, division, and the remainder which are +, -, *, /, and % respectively. Each of these is a binary operator that is, it requires two values (operands) to perform calculations.

We will discuss each type of Arithmetic operators in detail:

types of arithmetic operators

1.1. Addition Operator (+)

The arithmetic binary operator (+) adds the values of its operands and the result is the sum of values of its two operands. Its operands can be of integer type (int, short, byte, long, double) or float type (float and double).

For example:

4 + 20; results in 24. //adding two values.

num1 + 5; (where num1 = 5) results in 10. //adding a variable with a value.
num1 + num2; (where num1 = 6, num2 = 8) results in 14. //adding two variables
1.2. Subtraction Operator (-)

The – operator subtracts the second operand from the first. The operators may be of integer or float types.

For example:

10 - 3; //results in 7.

int num1 = 80;
int num2 = 15;
int result;
num2 - 9; //results in 6.
result = num1 - num2; //stores 65 in result variable.
1.3. Multiplication Operator (*)

The multiplication operator (*) multiplies the values of its operands. The values may be of integer or float types.

For example:

2.5 * 1.5; //results in 3.75 

int num1,num2;
num1 = 4,num2 = 6; 
num1 * num2; //results in 24.
1.4. Division Operator (/)

The division operator / divides its first operand by the second. Here, the operands may be of both integer or float types.

For example:

100/5; //evaluates to 20.

float num1 = 16.2;
num1 / 2; //evaluates to 8.1

float num2 = 2.5;
num1 / num2; //evaluates to 6.4
1.5. Modulus Operator (%)

The modulus operator % finds the modulus of its first operator relative to the second. That is, it produces the remainder of the division of the first operand by the second.

For example:

20 % 3; //evaluates to 2, since 3 * 6 = 18 and remainder is 2

-5 % -2; //evaluates to 1.

float num1 = 7.6, num2 = 2.9;
num1 % num2; //evaluates to 1.8
Operator + with Strings

We have used the operator ‘+’ with numbers. When we use + with the number, the result is also a number. In Java, we can also use the + operator for concatenating 2 strings.

For example:

“5” + “6”; //results into “56”

“20” + “ ,Sector A”; //results into “20 ,Sector A”

“Abc” + “123”; //results into “Abc 123”

5 + “xyz”; //results into “5xyz”
(Java would internally convert 5 into “5” first and then concatenate it with “xyz”).

Code Snippet to illustrate the concept of Arithmetic operators:

package com.TechVidvan.Operators;
public class ArithmeticOperators
{
  public static void main(String[] args)
  {
    int operand1 = 100, operand2 = 20;
    String stringName1 = "TechVidvan’s", stringName2 = " Java Tutorial";

    // using + operator with strings will concatenate the 2 strings
    System.out.println("Welcome to " +stringName1 +stringName2);

    // using addition + operator
    System.out.println("Adding(+) two operands: "+(operand1 + operand2));
    // using subtraction - operator
    System.out.println("Subtracting(-) two operands: "+(operand1 - operand2));
    // using multiplication * operator
    System.out.println("Multiplying(*) two operands: "+(operand1 * operand2));
    // using division / operator
    System.out.println("Dividing(/) two operands: "+(operand1 / operand2));
    // using modulus % operator
    System.out.println("Modulus(%) of two operands: "+(operand1 % operand2));
  }
}

Output:

Welcome to TechVidvan’s Java Tutorial
Adding(+) two operands: 120
Subtracting(-) two operands: 80
Multiplying(*) two operands: 2000
Dividing(/) two operands: 5
Modulus(%) of two operands: 0

2. Unary Operators in Java

The operators that act on one operand are called Unary Operators. They are of 2 types:

2.1. Unary +

The operator unary ‘+’ precedes an operand. The operand of the unary + operator must have an arithmetic type and the result is the value of the argument itself.

For example:

If number1 = 5 then +number1 means 5.
If number2 = -4 then +number1 means -4.

2.2. Unary –

The operator unary – precedes an operand. The operand of the unary – must be of an arithmetic type and the result is the negation of the value of the operand. This operator changes the sign of the operand’s value.

For example:

If number1 = 5 then -number1 means -5.
If number2 = 0 then -number1 means 0.
If number3 = -7 then -number3 means 7.

2.3. Increment/Decrement operators ( ++/– )

Java includes two useful operators which are generally not found in other computer languages (except C and C++). These are the increment (++) and decrement (- -) operators. The ++ operator adds 1 to its operand while – – operator subtracts 1. In other words, we can say,

num = num + 1;

is same as

++num ; or num++;

and,

num = num - 1;

is same as

--num ; or num-- ;

However, both the increment and decrement operators come in two categories/varieties: They can either precede or follow the operand.

The prefix version, in which the operator comes before the operand, as in-
Pre-Increment ( ++operand ) and Pre-Decrement ( – -operand ):

When an increment or decrement operator precedes its operand (prefix form), then Java performs the increment or decrement operation before using the value of the operand.

For example:

int count = 3,sum=0;
sum = sum + (++count); //will result in the value of sum to 4.

Principal: The pre-increment or pre-decrement operators follow the change-then-use rule that is, they first change the value of their operand, then use the new value in evaluating an expression.

And, in the postfix version, the operator comes after the operand, as in-
Post-Increment ( operand++ ) and Post-Decrement ( operand – – ):

When an increment or decrement operator follows its operand (prefix form), then Java first uses the value of the operand before performing the increment or decrement operation on the value of the operand.

For example:
int count = 3,sum=0;
sum = sum + (count++); //will result in the value of sum to 3.

Principal: The post-increment or post-decrement operators follow the use-then-change rule that is, they first use the value of their operand in evaluating the expression, then change the value of the operand.

Code Snippet to understand the increment/decrement operators:

package com.TechVidvan.Operators;
public class UnaryOperators
{
  // Java program to illustrate unary operators
  public static void main(String[] args)
  {
    int num1 = 10, num2 = 20, num3 = 30, num4 = 40, result;

    //using pre-increment operator
    result = ++num1;
    System.out.println("Value of pre incremented value of num1: " +result);

    //using post increment operator
    result = num2++;
    System.out.println("Value of post incremented value of num2: " +result);

    //using pre-decrement operator
    result = --num3;
    System.out.println("Value of pre decremented value of num3: " + result);

    //using post-decrement operator
    result = num4--;
    System.out.println("Value of post decremented value of num4: " +result);
  }
}

Output:

Value of pre incremented value of num1: 11
Value of post incremented value of num2: 20
Value of pre decremented value of num3: 29
Value of post decremented value of num4: 40

3. Relational Operators in Java

The term ‘relational’ in the relational operator refers to the relationships that values or operands can have with one another. Thus, the relational operators determine the relation among the operands. Java provides 6 relational operators for comparing numbers and characters.

But, relational operators do not work with strings. After the comparison, they return the result in boolean datatype. If the comparison is true, the relational operator results in true, otherwise false. They are extensively used in looping as well as conditional if-else statements.

The general syntax of the relational operator is,

variable_name relation_operator value;

The six relational operators are:types of relational operators

3.1. Equal to (==) Operator

It returns true if the left-hand side is equal to the right-hand side, otherwise false.

3.2. Not Equal to (!=) Operator

It returns true if the left-hand side is not equal to the right-hand side, otherwise false.

3.3. Less Than (<) Operator

It returns true if the left-hand side is less than the right-hand side, otherwise false.

3.4. Less Than or Equal to (<=) Operator

It returns true if the left-hand side is less than or equal to the right-hand side, otherwise false.

3.5. Greater Than (>) Operator

It returns true if the left-hand side is greater than the right-hand side, otherwise false.

3.6. Greater Than or Equal to (>=) Operator

It returns true if the left-hand side is greater than or equal to the right-hand side, otherwise false.

The below table illustrates the relational operations on p and q. Here p and q are of the int data type.

relational operators in java

4. Logical Operators in Java

Logical operators are also known as conditional operators. These operators are used for evaluating one or more boolean expression, for complex decision-making. They also return a boolean value (true or false).

There are three types of logical or conditional operators in Java are && (Logical-AND), || (Logical-OR) and ! (Logical NOT).types of logical or conditional operators

In this, && (Logical-AND) and || (Logical-OR) operators are the binary logical operators that work on two operands or expressions, while ! (Logical NOT) is a unary logical operator which works on single operand or expression.

Let’s discuss each of them in detail

4.1. The Logical AND Operator (&&)

The logical AND operator (&&) combines two expressions (operands) into one expression. The resulting expression evaluates to true only if both of its expressions (operands) are true. Following are the examples of && operator –

(5==3) && (4==4) //results into false because first expression is false.
(4==4) && (7==7) //results into true because both expressions are true.
1 < 8 && 4 > 2 //results into true because both expressions are true.
4 > 6 && 5 < 2 //results into false because both expressions are false.
4.2. The Logical OR Operator ( || )

The logical OR operator (||) also combines two expressions (operands) into one expression. The resulting expression evaluates to true if either of its expressions (operands) evaluates to true.

Following are the examples of || operator:

(6==3) || (4==4) //results into true because second expression is true.
(4==4) || (7==7) //results into true because both expressions are true.
6 < 9 || 4 < 2 //results into false because both expressions are false.
4 < 6 || 5 < 2 //results into true because first expression is true.
4.3. The Logical NOT Operator ( ! )

The logical NOT operator, which is written as ! , is a unary operator that works on a single operand or expression. The Logical NOT operator (!) negates or reverses the truth value of its operand.

That is if the expression is true, then !expression is false and vice-versa. The following are the examples of ! operator-

! (9 != 0) //results into false because 9 is non-zero(i.e., true).
! (6 > 2) //results into false because the expression 6 > 2 is true.
! (4 > 10) //results into true because the expression 4 > 10 is false.

Code Snippet to understand the Logical operators:

package com.TechVidvan.Operators;
public class LogicalOperators
{
  // Java program to illustrate Logical operators
  public static void main(String[] args)
  {
    int age = 19;
    String nationality = "Indian";
    int country_code = 22;

    //Using Logical AND (&&) operator
    if(age >=18 && nationality.equals("Indian"))
    {
      System.out.println("You are eligible for voting");
    }

    //Using Logical OR(||) operator
    if(age>=18 && (nationality.equals("Indian") || country_code==1))
    {
      System.out.println("You are eligible for voting");
    }

    //Using Logical NOT(!) operator
    if(country_code != 1)
    {
      System.out.println("You are NOT eligible for voting!!");
    }
  }
}

Output:

You are eligible for voting
You are eligible for voting
You are NOT eligible for voting!!

5. Bitwise Operators in Java

The Bitwise operators manipulate the individual bits of a number. The bitwise operators work with the integer types that is, byte, short, int, and long types. Java provides 4 bitwise operators:types of bitwise operators

The following table shows the 4 operations that Java programming language provides to perform bitwise functions on their operands:

Operator Use Operation
& op1 & op2 Bitwise AND
| Op1 | op2 Bitwise OR
^ op1 ^ op2 Bitwise XOR
~ ~op2 Bitwise Complement

The bitwise operations calculate each bit of their results by comparing the corresponding bits of the two operands on the basis of these 3 rules:

  • For AND operations, 1 AND 1 produce 1. Any other combination produces 0.
  • For XOR operations, 1 XOR 0 produces 1, similarly, 0 XOR 1 produces 1. Any other combination produces 0.
  • For OR operations, 0 OR 0 produces 0. Any other combination produces 1.
  • For complement operations, the operator inverts the value.
5.1. The Bitwise AND Operator (&)

It returns Bitwise AND operations on each parallel pair of bits of its every operand. The AND function sets the resulting bit to 1 only if the corresponding bits of both operands are 1, otherwise, the resulting bit is 0.

op1 op2 Result (op1 & op2)
0 0 0
0 1 0
1 0 0
1 1 1
5.2. The Bitwise OR Operator (|) / Inclusive OR Operator

It returns the Bitwise AND operations on each parallel pair of bits of its every operand. Inclusive OR means that if either of the two bits is 1, the resulting bit is 1. In short, at least one of the two bits should be 1 to get a result as 1.

op1 op2 Result (op1 | op2)

0

0

0

0

1

1

1 0

1

1 1

1

5.3. The Bitwise XOR operator (^) / exclusive OR Operator

Inclusive OR means that if the two bits of the operands are different, then the resulting bit is 1, otherwise the result is 0. If both bits are the same, the result is 0.

op1 op2 Result (op1 ^ op2)
0 0 0
0 1 1
1 0 1
1 1 0
5.4. The Bitwise Complement Operator (~)

The complement operator inverts the value of each bit of the operand; if the operand bit is 1 the result is 0 and if the bit is 0 the result is 1.

op1 Result (~op1)
0 1
1 0

Code Snippet to understand the Bitwise operators:

package com.TechVidvan.Operators;
public class BitwiseOperators
{
  public static void main(String args[])
  {
      int num1 = 11; //Binary form of 11 = 00001011
      int num2 = 22; //Binary form of 22 = 00010110
      int result;

      result = num1 & num2;
      System.out.println("Performing Bitwise AND operation");
      System.out.println("num1 & num2: "+result);

      result = num1 | num2;
      System.out.println("\nPerforming Bitwise OR operation");
      System.out.println("num1 | num2: "+result);

      result = num1 ^ num2;
      System.out.println("\nPerforming Bitwise XOR operation");
      System.out.println("num1 ^ num2: "+result);

      result = ~num1;
      System.out.println("\nPerforming Bitwise complement operation");
      System.out.println("~num1: "+result);
  }
}

Output:

Performing Bitwise AND operation
num1 & num2: 2
Performing Bitwise OR operation
num1 | num2: 31
Performing Bitwise XOR operation
num1 ^ num2: 29
Performing Bitwise complement operation
~num1: -12

6. Shift Operators in Java

A shift operator performs bit manipulation on operands by shifting the bits of its first operand to right or left.

The general syntax of shift operators is –

number shiftOperator numberOfPlacesToShift ;

There are 3 shift operators available in Java:types of shift operators

6.1. The Signed Left Shift Operator (<<)

The signed left shift operator shifts the bits of the number or operand to the left and fills 0 on vacated bits left as a result. Its effect is similar to multiplying the number with some power of two.

6.2. The Signed Right Shift Operator (>>)

The signed right shift operator shifts the bits of the number to the right. In a signed left shift operation, the leftmost vacated bits depend on the sign of the leftmost bit or sign bit or most significant bit (MSB) of the operand.

Its effect is similar to dividing the number with some power of two.

6.3. The Unsigned Right Shift Operator (>>>)

The unsigned right shift operator shifts the bits of the number to the right. In an unsigned right shift operation, the leftmost vacated bits are always set to 0, irrespective of the sign of the leftmost bit or sign bit or most significant bit (MSB).

Note:

In Java, the signed right shift operation populates the vacated bits with a sign bit, while the left shift and the unsigned right shift operation populates the vacated bits with zeroes.

To understand this, consider the example shown in the following figure:

shift operator example

Code Snippet to understand the shift operators:

package com.TechVidvan.Operators;
public class ShiftOperators
{
  public static void main(String args[])
  {
    int num1 = 16; //Binary form of 11 = 00010000
    int result;

    result = num1 << 2;
    System.out.println("Performing Left shift operation");
    System.out.println("num1 << 2: "+result);

    result = num1 >> 2;
    System.out.println("\nPerforming signed right shift operation");
    System.out.println("num1 >> 2: "+result);

    result = num1 >>> 2;
    System.out.println("\nPerforming unsigned right shift operation");
    System.out.println("num1 >>> 2: "+result);
  }
}

Output:

Performing Left shift operation
num1 << 2: 64
Performing signed right shift operation
num1 >> 2: 4
Performing unsigned right shift operation
num1 >>> 2: 4

7. Assignment Operator in Java (=)

Like other programming languages, Java offers an assignment operator = for assigning one value to another value or a variable.

Assignment Operator follows the right to left associativity, that is a value given on the right-hand side of the operator is assigned to the variable on the left-hand side and therefore we should declare the value of the right-hand side before using it or it should be a constant.

The general format of the assignment operator is,

variable = value;

For Example:

int x, y, z;
x = 9;
y = 7;
z = x + y;
z = z * 2;
Java Shorthand Assignment Operators

Java provides some special shorthand operators that simplify the coding of a certain type of assignment operations.

Using these shorthand operators, we can combine the assignment operator with other operators to build a shorter version of the statement, which is called a Compound Statement.

For example:

Instead of writing num = num + 5; we can write num += 5;.
The operator pair += tells the compiler to assign to num the value of num + 5. This shorthand works on all the binary operators in Java.

The general form of the Java shorthand assignment is:
var = var operator expression;
is same as
var operator = expression;

Following are some examples of Java shorthands:

x -= 10;	is equivalent to 	x = x - 10;
x *= 22;	is equivalent to 	x = x * 22;
x /= 3;		is equivalent to 	x = x / 3;
x %= y;		is equivalent to 	x = x % y;

Thus, we can say =, *=, /=, %=, +=, -= are assignment operators in Java. The operators *=, /=, %=, +=, -= are called arithmetic assignment operators.

The following table lists the shorthand assignment operators with their equivalents:

Shorthand Operator Use Equivalent to
+= op1 += op2 op1 = op1 + op2
-= op1 -= op2 op1 = op1 – op2
*= op1 *= op2 op1 = op1 * op2
/= op1 /= op2 op1 = op1 / op2
%= op1 %= op2 op1 = op1 % op2
&= op1 &= op2 op1 = op1 & op2
|= op1 |= op2 op1 = op1 | op2
^= op1 ^= op2 op1 = op1 ^ op2
<<= op1 <<= op2 op1 = op1 << op2
>>= op1 >>= op2 op1 = op1 >> op2
>>>= op1 >>>= op2 op1 = op1 >>> op2

Code Snippet to understand the Assignment operators:

package com.TechVidvan.Operators;
public class AssignmentOperators
{
  public static void main(String args[])
  {
    int num1 = 76;
    int num2 = 10;

    num2 += num1;
    System.out.println("+= Output: "+num2);

    num2 -= num1;
    System.out.println("-= Output: "+num2);

    num2 *= num1;
    System.out.println("*= Output: "+num2);

    num2 /= num1;
    System.out.println("/= Output: "+num2);

    num2 %= num1;
    System.out.println("%= Output: "+num2);
  }
}

Output:

+= Output: 86
-= Output: 10
*= Output: 760
/= Output: 10
%= Output: 10

8. Other Operators in Java

Java supports some other operators which are –

8.1. Ternary Operator ( ?: )

Java offers a shortcut conditional operator (?:) that stores a value according to the condition. This operator is a ternary operator that is it requires three operands.

The general form of the conditional/ternary operator is as follows:

expression1 ? expression2 : expression3 ;

The result of the whole expression depends on the value of expression1. If expression1 evaluates to true that is 1, then the value of expression2 is evaluated, otherwise, the value of expression3 is evaluated. For instance,
result = marks >= 50 ? “Pass” : “Fail” ;

The value of the variable result will be “Pass” if the test expression >= 50 evaluates to true (1), otherwise, the value of the result will be “Fail”.

Following are some more examples of ternary operator:

6 > 4 ? 9 : 7 evaluates to 9 because test expression 6 > 4 is true.
4 == 10 ? 10 :25 evaluates to 25 because test expression 4 == 10 is false.
8.2. The Dot . Operator

The dot operator (.) is used to access the instance members of an object or class members of a class.

For example:

class MyClass
{
int num1=10;
public static void main(String args[]){
MyClass object1 = new MyClass();
object1.num1 = 10; //using dot operator
}
8.3. The () Operator

This operator is used when we declare or call the methods or functions. We can list the method’s arguments between parenthesis (and) or we can specify an empty argument list by using () with nothing between them.

For example:

void display();
Int addNumbers(int x, int y);
8.4. The instanceof Operator

The instanceof operator is used for type checking. It tests whether its first operand is an instance of its second operand. It can be used to test whether an object is an instance of a class, a subclass or an interface. The general syntax is:

op1 instanceof op2;

It returns true or false in the result.

Code Snippet to understand the instanceof operator:

package com.TechVidvan.Operators;
public class InstanceofOperator
{
  public static void main(String[] args)
  {
      InstanceofOperator object1 = new 												InstanceofOperator();
      InstanceofOperator object2 = null;

      // As object1 is of type InstanceofOperator,it returns true
      System.out.println("object1 is instance of: InstanceOfOperator: "
          + (object1 instanceof InstanceofOperator));

      // As object2 is not instantiated, it returns false
      System.out.println("object2 is instanceof InstanceOfOperator: "
          + (object2 instanceof InstanceofOperator));

    }
}

Output:

object1 is instance of: InstanceOfOperator: true
object2 is instanceof InstanceOfOperator: false

Summary

Operators in Java are one of the most important and fundamental concepts. Operators help programmers to perform a few specific operations like Arithmetic, Unary, Assignment, Relational, Logical, Ternary, Bitwise, and Shift operation and get the valuable results out of them.

We can not get valuable results or information until and unless we use any of these operators in our program.By this article, we have learned each type of operator in Java along with their sub-categories.

Also, we understood the use of operators with the help of code snippets and examples given with each type of operator. Until and unless the basic knowledge and practical usage of operators are clear, one can not master the language.

Thank you for reading our article. If you have any queries, do let us know through the comment section below.