# Java Operators

In 
Published 2023-06-03

This tutorial explains to you how to use Java Operators. There are some examples as well.

In Java, we have :

  • Arithmetic Operators
  • Logical Operators
  • Assignment Operators
  • Unary Operators
  • Shift Operators
  • Relational Operators
  • Bitwise Operators
  • Ternary Operators

# Arithmetic Operators

Operators: +, -, *, /, % (modulo)

Example:

var x = 1 + 20 - 10;
System.out.println(x);

# Logical Operators

&& (logical AND)

|| (logical OR)

! (logical NOT)

Example:

// Returns false
System.out.println((1==1)&&(1==2));
// Returns true
System.out.println((1==1)&&(1==1));
// Returns true
System.out.println((1==1)||(1==2));
// Returns false
System.out.println(!(1==1));

# Assignment Operators

In Java we can use the following assignment operators:

Operator Example Equivalent to
= a = b a = b
+= a += b a = a + b
-= a -= b a = a - b
*= a *= b a = a * b
/= a /= b a = a / b
%= a %= b a = a % b

# Unary Operators

Unary operators are the operators used with only one operand. In Java we can use the following unary operators:

Operator Name Result
"+" Unary plus keep the value as it is (not generally used)
"-" Unary minus inverts the sign of an expression
"++" Increment operator increments a value by 1
"--" Decrement operator decrements a value by 1
"!" Logical complement operator inverts the value of a boolean

Example:

var x = 10;
++x;
// Prints 11
System.out.println(x);
--x;
// Prints 10
System.out.println(x);

# Shift Operators

The Shift Operators(<<, >>) are used to shift all the bits in a value to the left/right side of a specified number of times.

Example:

// Shift left "10" (binary) is transformed to "1000" (binary) = 8 (decimal)
System.out.println(2 << 2);

For testing the conversion you can use this converter.

# Relational Operators

In Java we can use the following relational operators:

Operator Name Example Result
== equal to 1 == 2 is not true
!= not equal to 1 != 2 is true
> greater than 1 > 2 is not true
< less than 1 < 2 is true
>= greater than or equal to 1 >= 2 is not true
<= less than or equal to 1 <= 2 is true

# Bitwise Operators

Bitwise operators work on bits and performs bit-by-bit operation.

In Java, we can use the following bitwise operators:

Operator Name Example Result
& bitwise AND a & b 0000 1100
| bitwise OR a | b 1000 1101
^ bitwise XOR (exclusive OR) a ^ b 1000 0001
~ complement ~ b 1111 0010

# Ternary Operators

A ternary operator is a simple replacement for if-then-else statement.

Its syntax is:

condition ? expression1 : expression2;

If the condition is "true", the operator will return "expression1", if not, the "expression2".

Example:

Integer examScore = 80;
String result = (examScore > 65) ? "PASS" : "FAIL";
// It prints "You PASS the exam."
System.out.println("You " + result + " the exam.");