Skip to content

Java Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

java
int x = 100 + 50;
int x = 100 + 50;

Java Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

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

Java Assignment Operators

Assignment operators are used to assign values to variables.

OperatorExampleSame As
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
&=x &= 3x = x & 3
|=x |= 3x = x | 3
^=x ^= 3x = x ^ 3
>>=x >>= 3x = x >> 3
<<=x <<= 3x = x << 3

Java Comparison Operators

Comparison operators are used to compare two values.

OperatorNameExample
==Equal tox == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equalx >= y
<=Less than or equalx <= y

Java Logical Operators

Logical operators are used to determine the logic between variables or values.

OperatorNameDescription
&&andReturns true if both statements are true
||orReturns true if one of the statements is true
!notReverse the result, returns false if the result is true

Java Bitwise Operators

Bitwise operators are used to perform bitwise operations on integers.

OperatorNameDescription
&ANDSets each bit to 1 if both bits are 1
|ORSets each bit to 1 if one of two bits is 1
^XORSets each bit to 1 if only one of two bits is 1
~NOTInverts all the bits
<<Zero fill left shiftShift left by pushing zeros in from the right and let the leftmost bits fall off
>>Signed right shiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
>>>Zero fill right shiftShift right by pushing zeros in from the left, and let the rightmost bits fall off

Java Ternary Operator

The ternary operator is shorthand for if-then-else statements.

java

int time = 20;

String result = (time < 18) ? "Good day." : "Good evening.";

System.out.println(result); // Outputs "Good evening."

int time = 20;

String result = (time < 18) ? "Good day." : "Good evening.";

System.out.println(result); // Outputs "Good evening."