Operators in Java

Java has a rich set of operators. Operators in Java are a symbol which is used to perform some operations on data. In this article, you’ll learn different types of operators in Java with examples. 

If you want to enrich your career and become a professional in Core Java, then visit Mindmajix - a global online training platform: "Core Java Online Training". This course will help you to achieve excellence in this domain.

List of Java Operators

The following topics will be covered in this Java Operators blog:

1. Java Operators

2. Java Operator Precedence

3. Associativity of operators in Java

What are Operators in Java

Let’s focus on What is Operators in Java one by one in detail.

#1. Arithmetic Operators in Java

Arithmetic Operators perform the same operations that they do in algebra for any mathematical expressions. 

The following table shows the various arithmetic operations available in Java:

OperatorNameDescription
+AdditionAdds two values
-SubtractionSubtracts one value from another
*MultiplicationMultiplies two values
/DivisionDivides one value by another
%Modulus – returns the remainder of a divisionReturns the division remainder
++IncrementIncreases the value of the variable by 1
--DecrementDecreases the value of the variable by 1

Java Arithmetic Operator Example

Now let us take an example of basic arithmetic operators for better insight. They all behave the same way they behave in algebra.

public class opTest{
     public static void main(String args[]) {
        System.out.println("Arithmetic Operators");
        int x = 2 + 3;
        int y = x * 2;
        int z = y / 2;
        int w = y - z;
        int m = -w; //in this case - operator will work us unary minus operator
        int n = 22 % 10;
        System.out.println("x = " + x);
        System.out.println("y = " + y);
        System.out.println("z = " + z);
        System.out.println("w = " + w);
        System.out.println("m = " + m);
        System.out.println("n = " + n);
        }
}

When we run this program, below output we get:

Output:

Arithmetic Operators

x = 5

y = 10

z = 5

w = 5

m = -5

n=2

[Related Article: Learn java Tutorial for Beginners]

#2. Assignment Operators in Java

In Java, Assignment operators are used to assign values to variables.

The following table shows the various types of assignment operators available in Java:

OperatorExample Equivalent
+=a+= 4a = a+4
-=b-= 5b = b-5
*=c*= 8c = c*8
/=d/= 3d = d/3
%=e%=5j <<= 10e = e%5
&=f&= 6f = f & 6
|=g |= 7g = g | 7
^=h ^= 8h = h ^ 8
>>=i >>= 9i = i >> 9
<<= j <<= 10j = j << 10

They are very useful as it saves a bit of typing and Java better implements them than their long forms. 

 MindMajix YouTube Channel

Example of Assignment Operator

Here is an example of showing their use:

public class Test {

   public static void main(String args[]) {
      int x = 10;
      int y = 20;
      int z = 0;

      z = x + y;
      System.out.println("z = x + y = " + z );

      z += x ;
      System.out.println("z += x  = " + z );

      z -= x ;
      System.out.println("z -= x = " + z );

      z *= x ;
      System.out.println("z *= x = " + z );

      x = 10;
      z = 15;
      z /= x ;
      System.out.println("z /= x = " + z );

      x = 10;
      z = 15;
      z %= x ;
      System.out.println("z %= x  = " + z );

      z <<= 2 ;
      System.out.println("z <<= 2 = " + z );

      z >>= 2 ;
      System.out.println("z >>= 2 = " + z );

      z >>= 2 ;
      System.out.println("z >>= 2 = " + z );

      z &= x ;
      System.out.println("z &= x  = " + z );

      z ^= x ;
      System.out.println("z ^= x   = " + z );

      z |= x ;
      System.out.println("z |= x   = " + z );
   }
}

Output:

z = x + y = 30

z += x  = 40

z -= x = 30

z *= x = 300

z /= x = 1

z %= x  = 5

z <<= 2 = 20

z >>= 2 = 5

z >>= 2 = 1

z &= x  = 0

z ^= x   = 10

z |= x   = 10

[Related Article: What are Different Classes And Objects In Java?]

#3. Unary Operators in Java

In Java, Unary operators are used to perform various operations like incrementing/decrementing a value one by one, negating an expression, or inverting the value of boolean.

NameOperatorDescription
Unary plus operator+It represents the positive value
Unary minus operator-It negates an expression
Logical complement operator!It inverts the value of a boolean
Increment operator++It increments a value by 1
Decrement operator--It decrements a value by 1

Java Unary Operator Example

class UnaryTrial {

    public static void main(String[] args) {

        int result = +1;
        // result is now 1
        System.out.println(result);

        result--;
        // result is now 0
        System.out.println(result);

        result++;
        // result is now 1
        System.out.println(result);

        result = -result;
        // result is now -1
        System.out.println(result);

        boolean success = false;
        // false 
        System.out.println(success);
        // true
        System.out.println(!success);
    }
}

#4. Bitwise Operators in Java

In Java, bitwise operators are used to perform manipulation of different bits of a number. There are several bitwise operators which can be used with any of the integral types ( int, short, char, etc.). Bitwise operator works on bits and performs the bit-by-bit operation. 

The following table lists the various bitwise operators −

OperatorExampleDescription 
Bitwise AND (&)(X & Y) will give 12, which is 0000 1100It copies a bit to the result if it exists in both operands.
Bitwise OR (|)(X | Y) will give 61, which is 0011 1101It copies a bit to the result if it exists in either operand.
Bitwise Complement (~)(~X ) will give -61, which is 1100 0011 in 2's complement form due to a signed binary number.It has the effect of flipping bits.
Bitwise XOR (^)(X ^ Y) will give 49, which is 0011 0001It copies the bit if it is set in one operand but not both.
Signed Right shift operator (>>)X >> 2 will give 15 which is 1111The left operand value is moved right by the no. of bits mentioned by the right operand.
Left shift operator (<<)X << 2 will give 240 which is 1111 0000The left operand value is moved left by the no. of bits mentioned by the right operand.
Unsigned Right shift operator (>>>)X >>>2 will give 15, which is 0000 1111The left operand value is moved right by the no. of the bits defined by a right operand and shifted values are filled up with zeroes.

#5. Relational Operators in Java

In Java, relational operators are used to compare two variables for equality, non-equality, less than, greater than etc. Java relational operators always return a boolean value, either true or false.

Operator Result
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Java Relational Operator Example

Here is the example showing the use of relational operators.

package com.mindmajix.java;

public class RelationalOperators {

	public static void main(String[] args) {

		int x = 10;
		int y = 20;

		System.out.println(x == y);
		System.out.println(x != y);
		System.out.println(x > y);
		System.out.println(x < y);
		System.out.println(x >= y);
		System.out.println(x <= y);

		// objects support == and != operators
		System.out.println(new Data1() == new Data1());
		System.out.println(new Data1() != new Data1());

	}

}

class Data1 {
}

Output:

false 

true 

false 

true 

false 

true 

false 

true 

Frequently Asked Core Java interview questions

#6. Logical Operators in Java

In Java, logical operators are used to check whether the expression is true or false.

OperatorNameDescription 
&&Logical andIf both statements are true, returns true.
||Logical orIf one of the statements is true, it returns true
!Logical notReverse the result (if the result is true, returns false)

#7. Ternary Operator in Java

The ternary operator in Java evaluates the test condition and executes a block of code based on the result of the condition. As the name ternary suggests, it is the only operator in Java consisting of three operands. It is written like the below syntax.

expr1? expr2: expr3

The meaning of this statement is: expr1 is evaluated and will result in some boolean value. If it is true then expr2 will be evaluated else expr3 will be evaluated. The only restriction is that both expr2 and expr3 must be of the same data type and cannot be void.

Java Ternary Operator Example

Let us look at one example to understand more.

class opTest {
public static void main(String args[]) {
        int i;
        String s;
        i = 10;
        s= i < 0 ? "Negative" : "Positive"; // get absolute value of i
        System.out.println(i + " is " + s);
        }
}

Output:

10 is Positive

[Related Article: Top 14 Java Frameworks]

Java Operator Precedence

Operators are special symbols that perform particular operations on one, two, or three operands. Precedence of operators in java determines the order in which operators in an expression are evaluated.

Below is the table showing the precedence order of all the Java operators according to their order:

Java Operator Precedence 
Operators Precedence 
postfix increment and decrement++--
prefix increment and decrement, and unary++ -- + - ~ !
multiplicative* / %
additive+-
shift<< >> >>>
relational< > <= >= instanceof
equality== !=
bitwise AND&
bitwise OR^
bitwise inclusive OR|
logical AND&&
logical OR||
ternary?:
assignment= += -= *= /= %= &= ^= |= <<= >>= >>>=

Associativity of operators in Java

If an expression has two operators with similar precedence, then according to the associativity, the expression is evaluated (either right to left or left to right). 

OperatorAssociativityPrecedence
postfix increment and decrementleft to right++--
prefix increment and decrement, and unaryright to left++ -- + - ~ !
multiplicativeleft to right* / %
additiveleft to right+-
shiftleft to right<< >> >>>
relationalleft to right< > <= >= instanceof
equalityleft to right== !=
bitwise ANDleft to right&
bitwise exclusive ORleft to right^
bitwise inclusive ORleft to right|
logical ANDleft to right&&
logical ORleft to right||
ternaryright to left?:
assignmentright to left= += -= *= /= %= &= ^= |= <<= >>= >>>=
 

Conclusion:

With this, we have come to the end of this Operators in Java blog. We hope now you understood what are Java operators, their types, the order in which operators precedence is evaluated and its associativity.

Explore Core Java Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Core Java TrainingNov 19 to Dec 04View Details
Core Java TrainingNov 23 to Dec 08View Details
Core Java TrainingNov 26 to Dec 11View Details
Core Java TrainingNov 30 to Dec 15View Details
Last updated: 03 Apr 2023
About Author

I am Ruchitha, working as a content writer for MindMajix technologies. My writings focus on the latest technical software, tutorials, and innovations. I am also into research about AI and Neuromarketing. I am a media post-graduate from BCU – Birmingham, UK. Before, my writings focused on business articles on digital marketing and social media. You can connect with me on LinkedIn.

read less
  1. Share:
Java Articles