Operators

An operator performs some operation on single or multiple operands and produces a result.

/* Most operators are binary or unary  
<left operand> operator <right operand>
<left operand> operator
*/

Arithmetic

OperatorDescription
+ Addition. Can be used with strings.
a = 23+b;
String nick="Nick"+10; // result string "Nick10"
String name=23 +"Name"+10; // result string "23Name10"
-Subtraction
int a = b-10;
*Multiplication
int a = b*10;
/ Division
a = b/10;
% Remainder
a = 24%10; // result 4
++ Increment. You can use postfix increment or prefix increment.
int ind=10;
ind++; // now ind equal to 11
int x = ind++; // now x equal to 11, ind equal to 12
int y = ++ind; // now y and ind equal to 13
-- Decrement. You can use postfix decrement or prefix increment.
int ind=10;
ind--; // now ind equal to 9

Relational

OperatorDescription
== Is equal to
if(a==34){
...
}
!=Not equal to
if(a!=34){
...
}
<Less than
boolean a = 23 < 45; // now a equal to true
<=Less than or equal to
boolean a = 46 <= 45; // now a equal to false
> Greater than
boolean a = 23 > 45;
>= Greater than or equal to
boolean a = 46 >= 45; 

Bitwise

OperatorDescription
& Bitwise and
 int a = 23&46; // now a equal to 6
| Bitwise or
int a = 23|46; // now a equal to 63
^ Bitwise xor
int a = 23^46; // now a equal to 57
~ Bitwise not
int a = ~23; // now a equal to -24
<< Bitwise left shift
int a = 23<<4;// now a equal to 368
>> Bitwise right shift
int a = 23>>4;// now a equal to 1
>>> The unsigned right shift. Shifts a zero into the leftmost position, while the leftmost position after >> depends on sign extension.
int a = 0xff>>>4;// now a equal to 15

Logical

OperatorDescription
&& Logical and
if(a&&b){
...
}
|| Logical or
if(a||b){
...
}
! Logical not
if(!a){
...
}

Assigment

OperatorDescription
= Assign
+= Add and assign
 a+=10; // same as a = a + 10;
-= Subtract and assign
*= Multiply and assign
/= Divide and assign.
%= Take the remainder and assign
&= Bitwise AND and assign
^= Bitwise XOR and assign
|= Bitwise OR and assign
<<= Bitwise left shift and assign
>>= Bitwise right shift and assign
>>>= Bitwise unsigned right shift and assign

Other operators

OperatorDescription
() Expression grouping or function call
(?:) Conditional operator; returns value based on the condition like if-else.
// syntax 
// expr ? val1 : val2
// if expr equal to true then return first value, otherwise second
int a= x>y ? 23 : 45 ;
instanceof Checks if the object is an instance of given type.

operator precedence

operators precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=