operators in Java

Below are Operators supported, in Java

Arithmetic operators

+(addition), -(subtraction), *(multiplication), /(dividedby), %(Modulo – reminder of division)
++(increment) x++; means x = x+1;

Difference between Pre increment and Post increment

Post increment
For eg, consider System.out.println(x++);
In above statement, first x is printed, and after that x is incremented

Pre increment
For eg, consider System.out.println(++x);
In above statement, first x is incremented, and after that x is printed

Similarly, pre and post increment can be used in other arithmetic expressions.

Difference between Pre decrement and Post decrement

Pre decrement and post decrement operator as well, can be used in arithmetic expressions.

Relational Operators or Comparison Operators

Relational or Comparison operators are used to perform comparison check between two variables or constants
x<3 (less than) > (greater than)
<= (less than or equal to) >= (greater than or equal to)
==( checking equal to),
!=(not equal to)

Generally Relational or Comparison expression evaluates to true or false.
Relational or Comparison operators are used with if, loops

Logical Operators

Logical operators are used two combine two or more Relational or Comparison expressions.
&&(Logical and): evaluates to true only if both operands are true

||(Logical or): evaluates to true, when either of the operand is true

!(Logical not): Negates logical expression, converts true to false, and vice versa

logical or and not takes two operands, where as logical not takes one operand

Assignment Operators

=, +=(short hand assignment)
-=, *=, /=, %=
x op= y means x=x op y;
For eg. x+=y means x=x+y;
X*=y; means x =x*y;

Conditional Operator or Ternary Operator


Conditional operator takes three arguments
relational_expression? expression_1 : expression_2;

If relational expression gets evaluated to true, expression_1 is returned, else expression_2 is returned.

Eg. b = (a == 15) ? 21 : 52;
As shown in above example, if value of a is 15, 21 is assigned to b, else 52 is assigned to b

Bitwise Operator

Bitwise operators perform operations on each binary representation
& – bitwise AND
| – bitwise OR
^ – bitwise XOR
<< - bit wise left shift >> – bit wise right shift

16 & 8
0010000(binary representation of 16)
0001000(binary representation of 8)
Result: 00000000

instanceof operator

instanceof example

We cannot overload operators in Java.How ever few operators like + has builtin overloading.

You may also like to read:
Basic data types in Java