Pages

Wednesday 7 August 2019

Operators


Agenda:
  • Increment and Decrement operators
  • Arithmetic operators
  • String concatenation operator
  • Relational operators
  • Equality operator
  • "instanceof" operator
  • Bitwise operator
  • Short circuit operators
  • Typecast operator
  • Assignment operator
  • Ternary operator
  •  New operator
  • [] operator
Increment & Decrement operators:
Pre increment  E.g.:  y = ++x;
Pre decrement  E.g.:  y = --x;
Postincrement  E.g. : y = x++;
Postdecrement E.g.:  y = x--;
  • In Preincrement or Predecrement first value gets increased or decreased then the assignment will happen(value is used).
  • But in Postincrement or Postdecrement first assignment(value is used) will happen then value gets increased or decreased.
For example:
1.     class Test{
2.     public static void main(String[] args){
3.     int x=10;
4.     int y=20;
5.     System.out.println(x++);
6.     System.out.println(++y);
7.     int a = 10;
8.     a = a++ +a + a-- -a-- + ++a;
9.     System.out.println(a);//(10 + 11 + 11 -10 + 10 = 32)
10. }
11. }
Output:
10
21
32

Note:
  • The evaluation of expression starts from Left to Right.
  • The value assignment starts from Right to Left.
  • Increment or decrement operators only valid for variables not for constant values.
  • E.g.: 10++ // invalid
  • Nesting of increment or decrement operators is not permitted.
  • E.g.: int x=10;
    int y =++(++x)//Compiler Error(It will become constant)
  • Increment or decrement operator for final variables are not permitted. 
  • E.g.: final int x =10;
    int y = ++x;//compiler Error.
  • Increment or decrement operator is not allowed on boolean variables.
Arithmetic Operators(+,-,*,/,%):

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

E.g.:
  • byte+byte = int
  • byte+short =int
  • byte+int = int
  • char + char = int
  • int + long = long
  • float +double = double
  • System.out.println('a'+1);//98
Infinity:
  • For Integral arithmetic(byte,short,int,long) there is no way to represent infinity or undefined results.
  • Hence, If infinity or undefined is the result then we will get ArithmeticException.
  • System.out.println(10/0);//AE
  • System.out.println(0/0);//AE
  • But for floating-point arithmetic(float, double) there is a way to represent infinity or undefined results.
  • For this Float and Double classes contains the following constants.
  • POSITIVE-INFINITY
  • NEGATIVE-INFINITY
  • NaN(Not a number)
  • Hence, If infinity or undefined results are the results we won't get any runtime exception.
E.g.:
1.     System.out.print(10/0.0);//+infinity
2.     System.out.println(10.0/0);//+infinity
3.     System.out.println(-10/0.0);//-infinity
4.     System.out.println(-10.0/0);//-infinity
5.     System.out.println(0/0.0);//NaN
6.     System.out.println(0.0/0);//NaN
7.     System.out.println(-0.0/0);//NaN
8.     System.out.println(-0/0.0);//NaN
Note:
  • ArithmeticException(AE) is a RuntimeException not compile-time exception.
  • AE is only for integral arithmetic not for floating-point arithmetic.
  • Only operators(/,%) causes AE.
String concatenation operator:
  • "+" is the only overloaded operator in java.
  • Sometimes "+" operator acts as arithmetic addition and sometimes it acts as concatenation.
  • If at least one argument is string type then "+" operator acts as concatenation.
  • If all arguments are number type then the "+" the operator acts as an additional operator.
For E.g.:
  • String a ="anu";
  • int b=10,c=20;
  • System.out.println(a+b+c);//anu1020
  • System.out.println(b+c+a);//30anu
Relational operators(>, <, >=, <=):
  • You can apply relational operators for every primitive type except boolean.
  • You can't apply relational operators for the object type.
  • You can't perform nesting of relational operators.
  • Ex: System.out.println(10<20<30);//Compiler Error.
Equality Operators(==, !=):
  • You can apply equality operators for every primitive type including boolean type also
  • You can also apply equality operators for an object reference.
  • Means, if you compare two objects reference r1,r2 using ==(double equal operator),
  • then r1==r2 return true if and only if both r1 and r2 pointing to the same object.
  • To use equality operator compulsory there should be some relationship between argument type(either parent-child or child-parent or same type),
  • otherwise, you will get a compiler error(incomparable types).
= = vs .equals():
  • = = operator compare address/location whereas .equals() compare content.
  • For E.g.:
  • String s1 = new String("anu");
  • String s2 = new String("anu");
  • System.out.println(s1==s2);//false
  • System.out.println(s1.equals(s2));//true
Instanceof operator:
  • You can use this operator to check whether the given object is of particular type or not.
  • syntax: <object reference> instanceof <class or interface name>
  • To use this operator compulsory there should be some relationship between argument type(either parent-child or child-parent or the same type), otherwise you will get a compiler error(incomparable types).
  • Whenever you are comparing parent object is child type or not by using instanceof operator then you will get false as output.
  • For any class or interface X, null instanceof X the result is always false.
Bitwise operators:
  • &(AND): If both the arguments are true then the result is true.
  • |(OR): If at least one argument is true, then the result is true.
  • ^(X-OR): If both are different arguments, the result is true.
  • System.out.println(true & false);//false
  • System.out.println(true | false);//true
  • System.out.println(true ^ false);//true
Note:
&, |, ^ : Applicable for both boolean and integral types.

Bitwise complement(~ tild operator):
  • It works with only Integral types.
  • It inverts all bits of its operand, means it convert 0 ---> 1 and 1---> 0
Trick
  • If value is +ve integer, then increase value by 1 and put negative prefix.
  • int a =10;
  • System.out.println(~a);// -11
  • If value is -ve integer, then decrease value by 1 and put positive prefix.
  • int a =-9;
  • System.out.println(~a);// 8
Boolean complement(!)  operator:
This operator is applicable only for boolean types not for integral types.
System.out.println(!false);// true

Short circuit(&&, ||) operators vs Bitwise operators(&, |)
  • In bit-wise operators both the argument should be evaluated while in short circuit operators the second argument is optional.
  • For example: 
  • r1&&r2, r2 will be evaluated if and only if r1 is true.
  • r1||r2, r2 will be evaluated if and only if r1 is false.
  • In bit-wise operator is applicable for both integral and boolean types while short circuit operator is applicable only for boolean types.
Typecast operator(primitive type-casting)
1.     Implicit typecasting.
2.     Explicit typecasting.
Implicit type casting:
  • The compiler is responsible for this typecasting.
  • Whenever you are assigning smaller data type value to the bigger data type variable this typecasting will be performed. Also known as widening or up-casting.
  • There is no loss of information in this typecasting.
  • The following are various possible implicit typecasting.
          

Explicit type casting
  • A programmer is responsible for this typecasting.
  • Whenever you are assigning bigger data type value to the smaller data type variable then explicit typecasting is required.
  • Also known as Narrowing or downcasting.
  • There may be a chance of loss of information in this typecasting.
  • Whenever you are assigning bigger data type value to the smaller data type variable by explicit typecasting the most significant bit(MSB) will be lost.
  • Whenever you are assigning floating-point data types to the integer data type by explicit typecasting the digits after the decimal the point will be lost.
  • E.g.:
  • float x =150.45f;
  • int i = (int)x;
  • System.out.println(i);//150
Assignment Operator:
Simple assignment operator:
E.g.: int x =10;
Chained assignment operator
int a,b,c,d;
a=b=c=d=20;
You can't perform chained assignment at the time of declaration.
E.g.: int a=b=c=d=20;
Compound assignment operator
  • += E.g.: int a+=1; is equivalent to int a=a+1;
  • -= E.g.: int a-=1; is equivalent to int a=a-1;
  • *= E.g.: int a*=1; is equivalent to int a=a*1;
  • /= E.g.: int a/=1; is equivalent to int a=a/1;
  • %= E.g.: int a%=1; is equivalent to int a=a%1;
  • &=
  • !=
  • ^=
  • >>=
  • >>>=
  • <<=
Conditional Operators:
  • Ternary operator(?:) is the only conditional operator in java.
  • int x = 10>20?30:40;
  • System.out.println(x);//40
  • You can perform nesting of Ternary operator.
  • int x =10>20?30:(50>10)?40:60;
  • System.out.println(x);//40
New operator:
  • You can use new operator to create an object.
  • In java, there is no delete operator for the destruction of the objects.
  • The garbage collector is responsible for destroying the objects.
[] operator:
  • You can use [] operator to declare and construct arrays.

Shift operators:
Right shift operators(>>):
  • It shifts binary bits to right.
  • e.g int a=4;int b=a>>2;
  • Here binary bits shift 2 position right and at empty place fill 0 if the number is +ve and if the number is -ve fill 1.
  • Assume the size of the int is 1 byte. So,4 will store in memory like 00000100 after shifting one position right and at empty place fill 0 (because the number is positive) It will become 00000010. Again shifting one position right it will become 00000001 and it's decimal value is 1 System.out.println(b);//1
Left shift operators(<<):
  • It shifts binary bits to left.
  • e.g int a=4; int b=a<<2;
  • Here binary bits shift 2 positions left and at empty place fill 0 either number is negative or positive.
  • Assume the size of the int is 1 byte. So,4 will store in memory like 00000100 after shifting one position left and at empty place fill 0. It will become 00001000
  • Again shifting one position left it will become 00010000 and its decimal value is 16
  • System.out.println(b);//16
Shift Right Zero Fill operator(>>>):
  • It  shifts binary bits to right and put 0 at the empty place(No matter number is +ve or -ve)
  • Its result will be always a positive number. 
  • e.g byte  a = -4;
  • int b =a>>>2;//111111111111111111111111111111(30 times 1)
  • System.out.println(b);//1073741823
Note: For shift, operator apply max(int, type of a, type of b);
E.g.: 
byte a=4;
int b=a>>2;
int c=a<<2;
int d=a>>>2;

Java operator precedence:
1.Unary operators:
[],x++,x--
++x,--x,~,!
new
2.Arithmetic operators:
*,/,%
+,-
3.Shift operators:
>>,>>>,<<
4.Comparision operators:
<,<=,>,>=,instanceof
5.Equality operators:
==,!=
6.Bitwise operators:
&,^,|
7.Short circuit operators:
&&,||
8.Conditional operators:
?:
9.Assignment operators:
+=,-=,*=,/+,%=

Next topic: CONTROL FLOW