Java Operators

Operators facilitate the execution of operations on variables and values.

In the following example, we apply the + operator to sum two values:

Example

int a = 111 + 77;

Though the + operator is primarily used to sum two values, as shown above, it can also combine a variable and a value, or two variables:

Example

int total1 = 100 + 50;      // 150 (100 + 50)
int total2 = total1 + 250;  // 400 (150 + 250)
int total3 = total2 + total2; // 800 (400 + 400)

Java classifies operators into these categories:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators




Arithmetic Operators

Arithmetic operators handle basic mathematical operations.

OperatorNameDescriptionExample
+AdditionAdds two valuesx + y
SubtractionSubtracts one value from anotherx – y
*MultiplicationMultiplies two valuesx * y
/DivisionDivides one value by anotherx / y
%ModulusReturns the division remainderx % y
++IncrementIncreases variable’s value by 1++x
DecrementDecreases variable’s value by 1–x




Java Assignment Operators

Assignment operators are utilized to allocate values to variables.

In the subsequent example, we employ the assignment operator (=) to assign the value 10 to a variable named b:

Example

int b = 10;

The addition assignment operator (+=) adds a specified value to a variable:

Example

int b = 10;
b += 5;


Here is a comprehensive list of assignment operators:

OperatorExampleEquivalent To
=b = 5b = 5
+=b += 3b = b + 3
-=b -= 3b = b – 3
*=b *= 3b = b * 3
/=b /= 3b = b / 3
%=b %= 3b = b % 3
&=b &= 3b = b & 3
|=x |= 3x = x | 3
^=b ^= 3b = b ^ 3
>>=b >>= 3b = b >> 3
<<=b <<= 3b = b << 3




Java Comparison Operators

Comparison operators are used to evaluate two values or variables. This is crucial in programming as it helps in determining outcomes and making decisions.

The result of a comparison is a Boolean value, which is either true or false. These concepts will be elaborated in the Booleans and If..Else chapters.

In the following example, we use the greater than (>) operator to ascertain if 5 exceeds 3:

Example

int a = 5;
int b = 3;
System.out.println(a > b); // returns true, because 5 is greater than 3
OperatorNameExample
==Equal tox == y
!=Not equal tox != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y




Java Logical Operators

Logical operators are employed to test for true or false values.

These operators define the logic between variables or values:

OperatorNameDescriptionExample
&&Logical andReturns true if both expressions are truex < 5 && x < 10
||Logical or
Returns true if one of the statements is true
x < 5 || x < 4
!Logical notInverts the result, returns false if the result is true!(x < 5 && x < 10)
Scroll to Top