Operators

Operators

Operator in Java is a symbol that is used to perform operations. Java operators are classified in to

  1. Increment and Decrement Operators
  2. Arithmetic Operators
  3. String concatenation Operators
  4. Relational Operators
  5. Equality Operators
  6. instanceof Operator
  7. Bitwise Operators
  8. Short circuit Operators
  9. Type cast Operators
  10. Assignment Operator
  11. Conditional Operator
  12. new Operator
  13. [] Operator
1. Increment and Decrement Operators
operator
Capture 1

Note 

  • We can apply increment and Decrement Operators only for variables but not for constant values. If we are trying to apply for constant values then we will get compile time error.

E.g

int x = 10;
int y = ++x;
System.out.println(y); // 11

int x = 10;
int y = ++20; // C.E: Unexpected type found: value required : variable
System.out.println(y);
  • Nesting of increment and decrement operators is not allowed otherwise we will get compile time error.

E.g

int x = 10;
int y = ++(++x); // C.E: Unexpected type found: value required : variable
System.out.println(y);
  • For final variables we can’t apply increment and decrement operators

E.g

final int x = 10;
int y = ++x; // C.E: Cannot assign a value to final variable x
System.out.println(y); 
  • We can apply increment and decrement operators for every primitive datatype except boolean.

E.g

boolean x = true;
int y = ++x; // C.E: Operator ++ cannot applied to boolean
System.out.println(y);

Difference between b++ and b = b + 1

If we apply any arithmetic operator between two variables a and b the result type is always max(int, type a, type b) .
E.g

byte a = 10;
byte b = 20;
byte c = a + b ; // C.E: Possible loss of precision found: int required: byte
System.out.println(c); 

byte c = (byte)(a+b); // Type casting
System.out.println(c); 30

byte b = 10;
byte c = b + 1 ; // C.E: Possible loss of precision found: int required: byte
System.out.println(c);

byte c = (byte)(b+1); // Type casting
System.out.println(c); 11

byte b = 10;
b++; // b = (byte) (b+1) [b++ means b = (type of b) (b+1)]
System.out.println(b); 11

Note

In the case of increment and decrement operators internal type casting will be performed automatically.

2. Arithmetic Operators
1411 operater 1

If we apply any arithmetic operator between two variables a and b the result type is always max(int, type a, type b) .

byte + byte = int
byte + short = int
short + short = int
byte + long = long
long + double = double
float + long = float
char + char = int
char + double = double

System.out.println(10+0.0); // 10.0
System.out.println('a'+'b'); // 97 + 98 = 195
System.out.println(100+'a'); // 197
Infinity

In the case of integral arithmetic (int, short, byte, long), there is no way to represent infinity. Hence if the infinity is the result then we are getting Runtime Exception saying ArithmeticException.

System.out.println(10/0); // R.E: ArithmeticException : / by zero

But in the case of floating point arithmetic (float, double) there is a way to represent infinity. For this Float and Double classes contains the following two constants.

POSITIVE_INFINITY = Infinity
NEGATIVE_INFINITY = -Infinity

Hence even though result is infinity we won’t get any ArithmeticException.

System.out.println(10/0.0); // Infinity
System.out.println(-10.0/0); // -Infinity
NaN (Not a Number)

In integral arithmetic there is no way to represent undefined results. Hence, if the result is undefined then we will get Runtime Exception saying ArithmeticException.

System.out.println(0/0); // R.E: ArithmeticException : / by zero

But in the case of floating point arithmetic there is a way to represent undefined results for this Float and Double classes contains NaN constant. Hence if the result is undefined we won’t get any ArithmeticException.

System.out.println(0/0.0); // NaN
System.out.println(-0.0/0); // Nan

Note

1. For any x value including NaN the following returns false

x < NaN // false
x <= NaN // false
x > NaN // false
x >= NaN // false
x == NaN // false 

2. For any x value including NaN the following expression returns true

x!NaN //true 
3. String Concatenation Operator
  • The only overloaded operator in Java is +
  • Some times it acts as arithmetic addition operator and some times acts as String concatenation operator.

E.g

int a = 10, b = 20, c = 30;
String d = "Ashok";
System.out.println(a+b+c+d); //60Ashok
System.out.println(a+b+d+c); //30Ashok30
System.out.println(d+a+b+c); //Ashok102030
System.out.println(a+d+b+c); //10Ashok2030
  • If at least one operand is string type then + operator acts as concatenation otherwise + acts as arithmetic addition operator. Hence System.out.println() is evaluated from left to right.

E.g

int a = 10, b = 20;
String c = "Ashok";
a = b + c; C.E: Incompatible type: Found: String, Required: int 
c = a + c; // Fine 
b = a + b; // Fine 
c = a + b; C.E: Incompatible type: Found:  int, Required: String 
4. Relational Operators
  • The Relational operators are >, >=, <, <=
  • We can apply relational operators for every primitive data type except boolean.

E.g:

1. 10 > 20 // false
2. 'a' < 'b' // true
3. 10 >= 10.0 // true
4. 'a' < 125 // true
5. true > false // C.E: Operator > cannot be applied to boolean, boolean
  • We can’t apply relational operators for object types

E.g:

"Ashok" >= "Vinod" //  C.E: Operator >= cannot be applied to String, String
  • Nesting of relational operators we are not allowed to apply

E.g:

System.out.println(10<20<30); // C.E: Operator < cannot be applied to boolean value
5. Equality Operators
  • The Equality operators are ==, !=
  • We can apply equality operators for every primitive data type including boolean.

E.g

10 == 20 // false
'a' == 'b' // false
10 == 10.0 // true
'a' == 125 // false
true != false // true
  • We can apply equality operators for object types
  • For the two object references r1 and r2 & r1 == r2 returns true if and only if r1 and r2 are pointing to the same object. i.e., equality operator is always meant for reference / address comparison.

E.g:

Student s1 = new Student();
Student s2 = new Student();
Student s3 = s1;
System.out.println(s1==s2); // false
System.out.println(s1==s3); // true
  • To apply equality operator between the object references compulsory there should be some relationship between the argument types (either parent to child or child to parent or some types). Otherwise we will get compile time error: Incomparable type.

E.g

Object o1 = new Object();
Thread t1 = new Thread();
Student s1 = new Student();
System.out.println(t1==s1); // C.E: Incomparable types
System.out.println(t1==o1); // false
System.out.println(s1==01); // false

Note

In general == operator meant for reference comparison where as .equals() meant for content comparison.

6. instanceof Operator

By using this operator we can check whether the given object is of a particular type or not.

Syntax

A instanceof B
Where 
A = Any reference type
B= Any class or interface

E.g

Thread t = new Thread();
System.out.println(t instanceof Thread); // true
System.out.println(t instanceof Object); // true
System.out.println(t instanceof Runnable); // true

To use instanceof operator, compulsory there should be some relationship between argument type, otherwise we will get compile time error saying Inconvertible type

Thread t = new Thread();
System.out.println(t instanceof String); // C.E: Inconvertible type found: Thread required: String
  • Whenever we are checking parent object is of  child type then we will get false as output.
Object o = new Object();
System.out.println(o instanceof String); // false
  • For any class or interface X, null instanceof X always returns false
System.out.println(null instanceof String); // false
7. Bitwise Operators
  • * The bitwise operators are &, |, ^
  • & – If both operands are true then result is true
  • | – If at least one operand is true then result is true
  • ^ – If both operands are different then result is true

E.g:

System.out.println(true & false); // false
System.out.println(true | false); // true
System.out.println(true ^ false); // true
Bitwise Compliment Operator(~)

We can apply bitwise compliment operator only integral types but not for boolean type.

E.g

System.out.println(~true); // C.E: Operator ~ cannot be applied for boolean type
System.out.println(~4); // -5
4 -- 0100
~4 -- 1011 (2's Compliment) // Here most significant bit is 1 so value is negative(-ve)
Finally add 1's compliment to 0100 i.e., 0101 (5) so output is -5

Note

  • The most significant bit represents sign bit. 0 means +ve and 1 means -ve number.
  • +ve numbers will be represented directly in the memory. Where as -ve numbers will be represented in the form of 2’s compliment
Boolean Complement Operator(!)

We can apply these operator only for boolean type not for integral types

E.g

System.out.println(!4); // C.E: Operator ! can't be applied to int
System.out.println(!false) // true
System.out.println(!true) // false
8. Short circuit Operators (&&,||)
  • We can use these operators just to improve performance of the system.
  • These are exactly same as normal bitwise operators &, | except the following difference.
Capture 2
  • x && y – y will be evaluated iff x is true
  • x || y – y will be evaluated iff x is false
package com.ashok.test;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class Test {
   public static void main(String[] args) {
      int a = 10, b = 15;
      if (++a < 10 & ++b > 15) {
         ++a;
      } else {
         ++b;
      }
      System.out.println(a + " " + b);
      int c = 10, d = 15;
      if (++c < 10 && ++d > 15) {
         ++c;
      } else {
         ++d;
      }
      System.out.println(c + " " + d);
   }
}

Output

Capture 3
9. Type cast Operators

There are two types of primitive type casting

  1. Implicit type casting
  2. Explicit type casting
1. Implicit type casting
  • Compiler is the responsible to perform this type casting
  • This type casting is required whenever we are assigning smaller data type value to the bigger data type variable
  • It is also known as “widening or up casting”
  • No loss of information in this type casting
widening type conversion
package com.ashok.test;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class Test {
    public static void main(String[] args)    {
      int i = 100; 
      long l = i; //no explicit type casting required  
      float f = l; //no explicit type casting required  
      System.out.println("Int value "+i);
      System.out.println("Long value "+l);
      System.out.println("Float value "+f);
    } 
}

Output

Int value 100
Long value 100
Float value 100.0
2. Explicit type casting
  • Programmer is responsible to perform this type casting
  • It is required when ever we are assigning bigger data type value to the smaller data type value
  • It is also known as “Narrowing or down casting”
  • There may be a chance of loss of information in this type casting
narrowing type conversion
package com.ashok.test;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class Test{
    public static void main(String[] args)    {
      double d = 100.04;  
      long l = (long)d;  //explicit type casting required  
      int i = (int)l; //explicit type casting required  
      System.out.println("Double value "+d);
      System.out.println("Long value "+l);
      System.out.println("Int value "+i);     
    }    
}

Output

Double value 100.04
Long value 100
Int value 100
10. Assignment Operators

There are 3 types of

  1. Simple assignment operators
  2. Chained assignment operators
  3. Compound assignment operators
1. Simple assignment operator

E.g:

int x = 10;
2. Chained assignment operator

E.g:

int a,b,c,d;
a=b=c=d=20;

We can’t perform chained assignment at the time of declaration.

E.g:

int a=b=c=d=20; //C.E 
3. Compound assignment operator

Some times we can mix assignment operator with some other operator to form Compound assignment operator. E.g:

int a = 10;
a+=20;
System.out.println(a); // 30 [a+=20 -- a = a+20 -- a = 10+20 -- a=30
  • The following are the various possible compound assignment operators in java
+=   assigns the result of the addition.
-=   assigns the result of the subtraction.
*=   assigns the result of the multiplication
/=   assigns the result of the division.
%=   assigns the remainder of the division.
&=   assigns the result of the logical AND.
|=   assigns the result of the logical OR.
^=   assigns the result of the logical XOR.
<<=  assigns the result of the signed left bit shift.
>>=  assigns the result of the signed right bit shift.
>>>= assigns the result of the unsigned right bit shift.
  • In compound assignment operators the required type casting will be performed automatically by the compiler.

E.g

byte b = 10;
b = b + 1; // C.E: Possible loss of precision found: int required: byte
System.out.println(b);

byte b = 10;
b = b ++;
System.out.println(b); // 11

byte b = 10;
b += 1;
System.out.println(b); // 11
11. Conditional Operator(? : )

The only ternary operator available in java is a ternary operator or conditional operator.

E.g

int a = 10, b = 20;
int x = (a>b) ? 40 : 50;
System.out.println(x); // 50 [a>b is True then 40 a>b is False then 50]
12. new Operator
  • We can use this operator for creation of objects.
  • In Java there is no delete operator because destruction of useless object is responsibility of garbage collector
13. [] Operator

We can use these operator for declaring and creating arrays.

Operators
Scroll to top