Java summary: Expressions

Parentheses () have three uses:
  1. Grouping to control order of evaluation, or for clarity.
    Eg, (a + b) * (c - d)
  2. After a method name to enclose parameters. Eg, x = sum(a, b);
  3. Around a type name to form a cast operator. Eg, i = (int)x;
Order of evaluation
  1. Higher precedence are done before lower precedence (see table).
  2. Left to right among equal precedence except: unary, assignment and conditional operators.

Abbreviations used below
i, j - integer (int, long, short, byte, char).
m, n - numeric values (integers, double, or float).
b, c - boolean; x, y - any primitive or object type.
s, t - String; a - array; o - object; co - class or object
Operator Precedence
. [] (args) post ++ --
! ~ unary + - pre ++ --
(type) new
* / %
+ -
<< >> >>>
< <= > >= instanceof
== !=
&
^
|
&&
||
?:
= += -= etc
Remember only:
  1. unary operators
  2. * / %
  3. + -
  4. comparisons
  5. && ||
  6. = assignments
Use () for all others

Arithmetic Operators

The result of arithmetic operators is double if either operand is double, else float if either operand is float, else long if either operand is long, else int.
n + m Addition. Eg 7+5 is 12, 3 + 0.14 is 3.14
n - m Subtraction
n * m Multiplication. Eg 3 * 6 is 18
n / m Division. Eg 3.0 / 2 is 1.5 , 3 / 2 is 1
n % m Remainder (Mod) after division of n by m. Eg 7 % 3 is 1
++i Add 1 to i before using the value in the current expression
--i As above for subtraction
i++ Add 1 to i after using the value in the current expression
i-- As above for subtraction

Comparing Primitive Values

The result of all comparisons is boolean (true or false).
== != < <= > >=

Logical Operators

The operands must be boolean. The result is boolean.
b && c Conditional "and". true if both operands are true, otherwise false. Short circuit evaluation. Eg (false && anything) is false.
b || c Conditional "or". true if either operand is true, otherwise false. Short circuit evaluation. Eg (true || anything) is true.
!b true if b is false, false if b is true.
b & c "And" which always evaluate both operands (not short circuit).
b | c "Or" which always evaluate both operands (not short circuit).
b ^ c "Xor" Same as b != c

Assignment Operators

= Left-hand-side must be a variable (an lvalue).
+= -= *= ... All binary operators (except && and ||) can be combined with assignment. Eg
a += 1 is the same as a = a + 1

Bitwise Operators

Bitwise operators operate on bits of integers. Result is int.
i & j Bitwise AND: 1 if both bits are 1. 5 & 3 is 1 (5=101, 3=011).
i | j Bitwise OR: 1 if either bit is 1. 5 | 3 is 7 (7=111).
i ^ j Bitwise EXOR: 1 if bits are different. 5 ^ 3 is 6 (6=110).
~i Bitwise NOT: 0 -> 1, 1 -> 0
i << j Bits in i are shifted j bits to the left, zeros inserted on right. 5 << 2 is 20.
i >> j Bits in i are shifted j bits to the right. Sign bits inserted on left. 5 >> 2 is 1.
i >>> j Bits in i are shifted j bits to the right. Zeros inserted on left.

Casts

(t)x Casts variable x to type t