Skip to content

Operators

This content is for Java. Switch to the latest version for up-to-date documentation.

Operators are symbols that perform operations on variables and values.

Operators in Java can be classified into 6 categories:

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison/Relational Operators
  4. Logical Operators
  5. Unary Operators
  6. Bitwise Operators

Arithmetic operators are used to perform arithmetic operations on variables and data.

OperatorDescriptionExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulus (remainder)a % b
++Incrementa++ or ++a
--Decrementa-- or --a
int sum = 5 + 3; // 8
int diff = 5 - 3; // 2
int product = 5 * 3; // 15
int quotient = 5 / 2; // 2 (integer division)
double exactQuotient = 5.0 / 2.0; // 2.5
int remainder = 5 % 2; // 1
int a = 5;
a++; // a is now 6
++a; // a is now 7 (prefix: increment then use)
a--; // a is now 6

Assignment operators are used in Java to assign values to variables.

OperatorDescriptionExampleEquivalent to
=Assignmenta = ba = b
+=Add and assigna += ba = a + b
-=Subtract and assigna -= ba = a - b
*=Multiply and assigna *= ba = a * b
/=Divide and assigna /= ba = a / b
%=Modulus and assigna %= ba = a % b
int x = 10;
x += 5; // x = 15
x -= 3; // x = 12
x *= 2; // x = 24
x /= 3; // x = 8
x %= 5; // x = 3

Relational operators are used to check the relationship between two operands.

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b
int a = 5;
int b = 7;
boolean isEqual = (a == b); // false
boolean isNotEqual = (a != b); // true
boolean isGreater = (a > b); // false
boolean isLess = (a < b); // true
boolean isGreaterOrEqual = (a >= b); // false
boolean isLessOrEqual = (a <= b); // true

Logical operators are used to check whether an expression is true or false.

OperatorDescriptionExample
&&Logical ANDa && b
||Logical ORa || b
!Logical NOT!a
boolean a = true;
boolean b = false;
boolean andResult = a && b; // false
boolean orResult = a || b; // true
boolean notResult = !a; // false

Unary operators are used with only one operand.

Bitwise operators in Java are used to perform operations on individual bits.

OperatorDescriptionExample
&Bitwise ANDa & b
|Bitwise ORa | b
^Bitwise XORa ^ b
~Bitwise NOT~a
<<Left shifta << n
>>Right shifta >> n
>>>Unsigned right shifta >>> n
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int bitwiseAnd = a & b; // 0001 -> 1
int bitwiseOr = a | b; // 0111 -> 7
int bitwiseXor = a ^ b; // 0110 -> 6
int bitwiseNot = ~a; // 1010 -> -6 (in two's complement)
int leftShift = a << 1; // 1010 -> 10
int rightShift = a >> 1; // 0010 -> 2
Built with passion by Ngineer Lab