CORE JAVA

ProwessApps Learning Portal

Operators in Java


Expression :
  • An expression is anything which evaluates to something.

  • Expressions are combinations of operators and operands.

Operator :

Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.

Operator's Categories:
  1. Unary : A unary operator is an operator, which operates on one operand.

  2. Binary : A binary operator is an operator, which operates on two operands.

  3. Ternary : A ternary operator is an operator, which operates on three operands.


TYPES OF OPERATOR :-
  1. Arithmetic Operator
    [ +, -, *, /, % ]

  2. Assignment Operator
    [ =, +=, -=, *=, /=, %= etc...]

  3. Increment / Decrement Operator
    [ ++, -- ]

  4. Relational Operator
    [ >, <, >=, <=, !=, == ]

  5. Logical Operator
    [ &&, ||, ! ]

  6. Bitwise Operator
    [ &, |, ^, ~ ]

  7. Conditional Operator
    [ ? : ]


1 . Arithmetic Operator :

Arithmetic operator in Java behaves as one would expect.

OperatorExample
+ ( Addition ) 4+x+5+y
- ( Subtraction ) 4-x-5-y
* ( Multiplication ) 4*x*5
/ ( Division ) 50/x
% ( Modulus )
Divides left-hand operand by right-hand operand and returns remainder.
9%4
result = 1
Compound expression:
      3*x+5-7
      principle + (principle + interest)
2 . Assignment Operator
  • The assignment operator has the lowest precedence of all operator.

  • It is always evaluated last.

  • Assignment can be used to assign the value of an expression to a variable.

  • In assignment, the previous value of the variable is overwritten by the value of the expression.

    variable = expression
    Example:
    x = x+10
    isVisible = true;
    timeInSecond = distance/speedOfLight;

1. Add Assignment +=
int a = 20;
//add 5 to a
a += 5; similar to  a = a+5;
System.out.print(a);
[OUTPUT : 25]
-----------------------------
2. Multiply Assignment *=
int a = 20;
//multiply 5 to a
a *= 5; similar to a = a*5;
System.out.print(a);
[OUTPUT : 100]
-----------------------------
Similarly, we have
-=, ;/=, %=, <<=, >>=, &=, ^=, |=

3 . Increment (++) / Decrement (--) Operator
  • These operators are used to increment or decrement the variables's value by 1.

  • They are unary operator.

  • Increment / Decrement operators are used in two ways:
    Post-fix notation : var++ or var--
    Pre-fix notation   : ++var or --var

Post-fix notation

When post-fix notation is used, the result is evaluated first and then the operation (inc / dec) is performed.

Pre-fix notation

When pre-fix notation is used, the operation (inc / dec) is performed first then the result is evaluated.

e.g.
// x initialized to 5
int x = 5; 
int y = x++; (postfix)
//y assigned the value of x
//x is incremented 
[RESULT : x = 6, y = 5]
---------------------------
int z = ++x; (prefix)
//x is incremented
//a assigned the value of x
[RESULT : x = 6, z = 6]
                
4 . Relational Operator

Relational Operators are used to compare two values. Relational expression always evaluates result as boolean either true or false.

1. Greater Than: >
int a = 5, b = 10;
( a > b ) [Result: false]
-----------------
2. Less Than: < 
int a = 5, b = 10;
( a < b ) [Result: true]
-----------------
3. Equal To: ==
int a = 5, b = 5;
( a == b ) [Result: true]
------------------
4. Not Equal To: !=
int a = 5, b = 2
( a != b ) [Result: true]
--------------------
5.Greater Than or Equal: >=
int a = 10, b = 5;
( a >= b ) [Result: true]
-----------------
6.Less Than or Equal: <= 
int a = 10, b = 5;
( a <= b ) [Result: false]

5 . Logical Operator
Logical Expression

An expression whose value is a boolean type ( true or false ).

Logical operators are used when we want to compare more than one relation at a time.

Logical operators:
  1. Logical AND ( && ):
    exp1 && exp2
    Logical AND true when both expressions are true.
    Logical AND false when one of the expression is false
    .
    Truth Table:
    Exp1Exp2Result
    truetruetrue
    truefalsefalse
    falsetruefalse
    falsefalsefalse
  2. Logical OR ( || ):
    exp1 || exp2
    Logical OR true when one of the expression is true.
    Logical OR false when when both expressions are false
    .
    Truth Table:
    Exp1Exp2Result
    truetruetrue
    truefalsetrue
    falsetruetrue
    falsefalsefalse
  3. Logical NOT ( ! )
    !expr
    It flips the result.
    Logical Not is true when the expression is false.
    Logical NOT is false when the expression is true
    .
    Truth Table:
    ExprResult
    truefalse
    falsetrue

Example:

1. Logical AND ( && ) 
int x = 6;
boolean b = (x > 5)&&(x < 10);
System.out.print( b );

[OUTPUT: true]

int x = 6;
boolean b = (x > 5)&&(x !=6);
System.out.print( b );

[OUTPUT: false]
-------------------------
2. Logical OR ( || ) 
int x = 6;
boolean b = (x > 5)||(x !=6);
System.out.print( b );

[OUTPUT: true]
-------------------------
3. Logical NOT ( ! ) 
int x = 6;
boolean b = !(x > 5)
System.out.print( b );

[OUTPUT: false]
-------------------------

6 . Bitwise Operator :

Bitwise operators performs operations on bits.
AND ( & ),  OR ( | ),  XOR ( ^ ),  NOT ( ~ ).

Truth Table:
----------------------------------
A   B    A&B   A|B    A^B    ~A
----------------------------------
0   0    0      0     0       1
----------------------------------
0   1    0      1     1       1
----------------------------------
1   0    0      1     1       0
----------------------------------
1   1    1      1     0       0
----------------------------------
                        
Example :
class Test
{
public static void main(String []arg)
  {
   int a = 6;
   int b = 3;
   int r1 = a & b;
   int r2 = a | b;
   int r3 = a ^ b;
   int r4 = ~a;
   System.out.print(r1);
   System.out.print(", "+r1);
   System.out.print(", "r1);
   System.out.print(", "r1);
  }
}

[ OUTPUT: 2, 7, 5, -7 ]

DESCRIPTION
    a = 0000 0110
    b = 0000 0011
 ---------------------
  a&b = 0000 0010 = 2
 ---------------------
  a|b = 0000 0111 = 7
 ---------------------
  a^b = 0000 0101 = 5
 ---------------------
  ~a  = 1111 1001 = -7
 ---------------------
In ~a the first bit(Most significant 
bit ) is 1 that represents number
is negative, so for negative values
system evaluates 2s compliment
of the bit and print magnitude
with minus (-) symbol. 
   So,
       ~6 = 1111 1001
 1s 0f ~6 = 0000 0110
                   +1
 ---------------------
 2s of ~6 = 0000 0111 = 7
----------------------
so, result is -7.

7 . Conditional Operator ( ? : )

Conditional operator is also known as the ternary operator. It takes three operands and evaluates the boolean expression.

prowessapps.com

Example:

public class Test
{
 public static void main(String []arg)
 {
  int a = 10, b = 20, max;
  max = ( a > b) ? a : b;
  System.out.print("Max = "+max);
 }
}
            
OUTPUT:
Max = 20

8. Shift Operator (<<, >>, >>>) :

Shift operator are used to shift the bits of a number towards left or right.

1. Left Shift Operator      : <<
2. Right Shift Operator   : >>
3. Unsigned Right Shift  : >>>

Syntax :

   n ShiftOperator t

Here :
n : Perform shift on n's bits.
t : number of times.

Example:

1. Left Shift ( << ) 
class Test
{
 public static void main(String []arg)
 {
  int x = 6 << 2;
  System.out.print(x);
 }
}

  [ OUTPUT : 24]
-----------------------------------
2. Right Shift ( >> ) 
class Test
{
 public static void main(String []arg)
 {
  int x = 6 >> 2;
  System.out.print(x);
 }
}

  [ OUTPUT : 1]
-----------------------------------
3. Unsigned Right Shift ( >>> ) 
class Test
{
 public static void main(String []arg)
 {
  int x = 6 >>> 2;
  System.out.print(x);
 }
}
  [ OUTPUT : 1]
-----------------------------------
For negative number, >>> changes parity bit (MSB) to 0 
-----------------------------------
DESCRIPTION :
  6 << 2 means :
  We need to perform left shift on bits of 6, 2 times

          6 = 0000 0110
first time  = 0000 1100
second time = 0001 1000 = 24

  6 >> 2 means :
  We need to perform right shift on bits of 6, 2 times

          6 = 0000 0110
first time  = 0000 0011
second time = 0001 0001 = 1


Operator Precedence:

If more than one operators are involved in an expression, Java language has a predefined rule of priority for the operators that decides which operator evaluate first. This rule of priority of operators is called operator precedence.

prowessapps.com

NOTE : two operators the same precedence will be evaluated based on their associativity. Usually, associativity is evaluated from left to right. Associativity of assignment is right to left.


instanceof Operator :

This operator is used only for object reference variables. The operator checks whether the object is of a particular type (class type or interface type).

Syntax:

(ref.var) instanceof (class/interface type)

class Test
{
 public static void main(String []arg)
 {
  String name = "Ayan";
/* it returns true since name is 
   type of String */
 boolean res = name instanceof String;
 System.out.println( res );
 }
}  
OUTPUT:
true  




advertisement