Operators

Operators perform specific operations on one or more operands, and return a result.

Arithmetic operators

Table 1. List of supported arithmetic operators
Operator Description Example Result
+ Additive operator 12+3 15
- Subtraction operator 12-2 10
* Multiplication operator 12*50 300
/ Division operator 12/2 6
% Remainder operator 10%3 1
The + operator can also be used to concatenate strings. For example:
String name ="John"+" "+"Doe"

Comparison operators

The following operators can be applied to all types:

Table 2. List of supported comparison operators
Operator Description Example Result
== Equal to 12 == 5 false
!= Not equal to 12 != 5 true

The following operators can be applied to numeric types only:

Table 3. List of supported comparison operators
Operator Description Example Result
> Greater than 12 > 5 true
>= Greater than or equal to 12 >= 5 true
< Less than 12 < 5 false
<= Less than or equal to 12 <= 5 false

Logical operators

Logical operators operate on Boolean values.

Table 4. List of supported logical operators
Operator Description Example Result
! Logical NOT !true false
& Logical AND true & false false
| Logical OR true | false true
^ Logical XOR (exclusive OR) true ^ false true
&& Conditional AND true && false false
|| Conditional OR true || false true

With conditional operators, the second operand is evaluated only if necessary.

Bitwise operators

Bitwise operators operate on individual bits. They can be applied on integer values such as long, int, short, and byte.

Table 5. List of supported bitwise operators
Operator Description Example Result
~ Binary complement ~0 255
& Binary AND 6 & 2 2
| Binary OR 6 | 1 7
^ Binary XOR (exclusive OR) 6 ^ 2 4
<< Signed left shift 10 << 1 20
>> Signed right shift operator 10 >> 1 5
>>> Unsigned right shift -50 >>> 2 51

Assignment operators

The assignment operator is used to assign a value to a variable. It is denoted by a single equal sign (=).

name = "John Doe"

The assignment operator can also be combined with arithmetic operators.

x += 5

In this example, 5 is added to the variable x. It is equivalent to x = x + 5.

instanceof operator

The instanceof operator is a comparison operator that can be used to test if an object is of a given type.

Person person = ...
Customer customer =null;
if (person instanceof Customer)
  customer = (Person)person;

?: operator

The ?: operator is a ternary conditional operator. It is a condensed form of the if-else construct.

max = (x > y) ? x : y;

The first operand must be a Boolean expression.