Skip to content

Operators

Keyhan Hadjari edited this page Sep 7, 2016 · 3 revisions
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 = += -= *= /= %= &= ^= |= <<= >>= >>>=

Assignment operators

They look like "=" , "+="

public void foo() {
int i = 0;
System.out.println(i++); // prints 0
System.out.println(i); // prints 1
}

Post-fix operators

They look like "i++" or "i--"

public void foo() {
int i = 0;
System.out.println(i++); // prints 0
System.out.println(i); // prints 1
}

Pre-unary operators

They look like "++i" or "--i"

public void foo() {
int i = 0;
System.out.println(++i); // prints 1
System.out.println(i); // prints 1
}

Arithmetic operators

public void foo() {
int i = 1, j = 3;
System.out.println(i + j); // prints 4
System.out.println(i - j); // prints -2
System.out.println(i * j); // prints 0
System.out.println(i / j); // prints 0
}

Normal Operands

  • The “==” Operator compares the memory locations, which is never same for different objects whereas equals() compares the contents
  • By contract, if two objects are equivalent according to the equals() method, then the hashCode() method must evaluate them to be ==.
  • The “=” operand will get its meaning the first time used if a string starts before the operand then concat will be done otherwise a mathematical +. If digit starts and finish with string then the last “+” will concat all the rest will be mathematical +.
  • The ++i increments i by one and returns the new value
  • The i++ increments i by one but returns the old value
int i = 5;
System.out.println(++i); //i is now 6 and Prints 6
System.out.println(i++); //i is now 7 but Prints 6

Bitwise Operands

Using the bitwise operator can circumvent short-circuiting behavior: boolean b = booleanExpression1() && booleanExpression2(); boolean b = booleanExpression1() & booleanExpression2(); If booleanExpression1() evaluates to false, then booleanExpression2() is not evaluated in the first case, and booleanExpression2() (and whatever side-effects it may have) is evaluated in the second case,

  • X & Y is bitwise AND
  • X | Y is bitwise OR
  • X ^ Y is bitwise XOR

The operators &, ^, and | are bitwise operators when the operands are primitive integral types. They are logical operators when the operands are boolean

Clone this wiki locally