Monday, July 25, 2022

Operators_&_Assignments

Increment & Decrement operators 

The following table will demonstrate the use of increment and decrement operators.


1. Increment & decrement operators we can apply only for variables but not for constant values.other wise we will get compile time error

Example 1:
    int x = 4;
    int y = ++x; 
    System.out.pritnln(y); 
output : 
    5

Example 2:
    int x = 4;
    int y = ++4; 
     System.out.pritnln(y);
Output:
    C.E: unexpected type required: varialbe found : value

2. We can't perform nesting of increment or decrement operator, other wise we will get compile time error.

Example1 :

class Test { public static void main(String[] args){ int x = 4 ; int y = ++(++x); System.out.println("Value of Y : "+y); } }
Output:
    compile time error : Unexpected Typ
    required: varialbe
    found : value

3. For the final variables we can't apply increment or decrement operators ,other wise we will get compile time error

Example1 :
class Test { public static void main(String[] args){         final int x = 4;      x++; // x=x+1      System.out.println(x); } }

Output :
    C.E : can't assign a value to final variable 'x' .

4. We can apply increment or decrement operators even for primitive data types except boolean.

Example 1:
   int x=10;
    x++; 
    System.out.println(x);
Output :
    11
   
Example 2:
    char ch='a';
    ch++; 
    System.out.println(ch); //b

    double d=10.5;
    d++;
    System.out.println(d); //11.5

    boolean b=true;
    b++;
    System.out.println(b); //CE : operator ++ can't be applied to boolean

Difference between b++ and b = b+1?
If we are applying any arithmetic operators b/w 2 operands 'a' & 'b' the result type is max(int , type of a , type of b)

Example 3:
   byte a=10;
   byte b=20;
   byte c=a+b;
   System.out.println(c);
Output :
   CE : possible loss of precession found : int required : byte
   //byte c=byte(a+b); valid

Example 4:
   byte b=20;
   byte b=b+1; 
   //byte b=(byte)b+1 ; valid System.out.println(c);
Output :
    CE : possible loss of precession found : int required : byte

In the case of Increment & Decrement operators internal type casting will be performed automatically by the compiler
b++;  => b=(type of b)b+1;

Example 5:
   byte b=10;
   b++;
   System.out.println(b); 
Output: 
   11

Arithmetic Operator 

1. If we apply any Arithmetic operation b/w  variables a & b , the result type is always max(int , type of a , type of b)

Example :

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

   System.out.println('a' + 'b'); // output : 19 
   System.out.println('a' + 1); // output : 98
   System.out.println('a' + 1.2); // output : 98.2
2. In integral arithmetic (byte , int , short , long) there is no way to represents infinity , if infinity is the result we will get the ArithmeticException / by zero 

System.out.println(10/0); // output RE : ArithmeticException / by zero
But in floating point arithmetic(float , double) there is a way represents infinity. System.out.println(10/0.0); // output : infinity


For the Float & Double classes contains the following constants : 
  1. POSITIVE_INFINITY
  2. NEGATIVE_INFINITY
Hence, if infinity is the result we won't get any ArithmeticException in floating point arithmetics.

Example :
    System.out.println(10/0.0); // output : infinity
    System.out.println(-10/0.0); // output : - infinity
3. NaN(Not a Number) in integral arithmetic (byte , short , int , long) there is no way to represent undefine the results. Hence the result is undefined we will get ArithmericException in integral arithmetic

System.out.println(0/0); // output RE : ArithmeticException / by zero
But floating point arithmetic (float , double) there is a way to represents undefined the results .

For the Float , Double classes contains a constant NaN , Hence the result is undefined we won't get ArithmeticException in floating point arithmetics . 

Example :
    System.out.println(0.0/0.0); // output : NaN
    System.out.println(-0.0/0.0); // output : NaN
4. For any 'x' value including NaN , the following expressions returns false


Example :
     System.out.println(10 < Float.NaN );     //false
    System.out.println(10 <= Float.NaN );    //false
    System.out.println(10 > Float.NaN );    //false
    System.out.println(10 >= Float.NaN );    //false
    System.out.println(10 == Float.NaN );    //false
    System.out.println(Float.NaN == Float.NaN );    //false

    System.out.println(10 != Float.NaN );    //true
    System.out.println(Float.NaN != Float.NaN );    //true
5. ArithmeticException :
  • It is a RuntimeException but not compile time error
  • It occurs only in integral arithmetic but not in floating point arithmetic.
  • The only operations which cause ArithmeticException are : ' / ' and ' % '




String Concatenation operator 

  • The only overloaded operator in java is ' + ' operator some times it access arithmetic addition operator & some times it access String concatenation operator.
  • If acts as one argument is String type , then '+' operator acts as concatenationand If both arguments are number type , then operator acts as arithmetic operator.

Example :

    String a="ashok";
    int b=10,c=20,d=30; 

    System.out.println(a+b+c+d); //output : ashok102030
    System.out.println(b+c+d+a); //output : 60ashok
    System.out.println(b+c+a+d); //output : 30ashok30 
    System.out.println(b+a+c+d);  //output : 10ashok 2030

Example :



 



Example :


consider the following declaration String a="ashok";
int b=10 , c=20 , d=30 ;
  
Example :
   a=b+c+d ;
Output:
   CE : incompatible type
        found : int
   required : java.lang.String

Example :
   a=a+b+c ; // valid
 
Example :
   b=a+c+d ; 11.
Output:
   //CE : incompatible type
   found : java.lang.String
   required : int 15. Example :

Example :
   b=b+c+d ; // valid  
 }
Relational Operators(< , <= , > , >= )
We can apply relational operators for every primitive type except boolean.
Example:
   System.out.println(10 < 10.5); //true
   System.out.println('a' > 100.5); //false
   System.out.println('b' > 'a'); //true
   System.out.println(true > false); //CE : operator > can't be applied to boolean       boolean

We can't apply relational operators for object types



ExampleSystem.out.println("ashok123" > "ashok");
Output:   // CE: operator > can't be applied to java.lang.String ,Java.lang.String

Note : Nesting of relational operator is not allowed

Example: System.out.println(10 > 20 > 30); // System.out.println(true > 30);
Output: //CE : operator > can't be applied to boolean , int

Equality Operators : (== , !=)
We can apply equality operators for every primitive type including boolean type also
Example: 
      System.out.println(10 == 20) ; //false 
      System.out.println('a' == 'b' ); //false 
      System.out.println('a' == 97.0 ) //true 
      System.out.println(false == false) //true
We can apply equality operators for object types also .

For object references r1 and r2, r1 == r2 returns true if and only if both r1 and r2 point to the same object. i.e., == operator meant for reference-comparison Or address-comparison.

Example :  
      Thread t1=new Thread( ) ;
      Thread t2=new Thread( );
      Thread t3=t1 ;
      System.out.println(t1==t2); //false 
      System.out.println(t1==t3); //true



To use the equality operators between object type compulsory these should be some relation between argument types(child to parent , parent to child) , Otherwise we will get Compiletime error incompatible types

Example:
   Thread t=new Thread( ) ;
   Object o=new Object( );
   String s=new String("Cloud");
   System.out.println(t ==o); //false
   System.out.println(o==s); //false 

 

 System.out.println(s==t); //CE : incompatible types : java.lang.String and            
 java.lang.Thread


For any object reference of on r==null is always false , but null==null is always
true.

Example:
   String s= new String("ashok");
   System.out.println(s==null); //output : false
   String s=null ;
   System.out.println(r==null); //true
   System.out.println(null==null); //true
What is the difference between == operator and .equals( ) method ?
In general we can use .equals( ) for content comparision where as == operator

Example:
   String s1=new String("ashok");
   String s2=new String("ashok"); 
   System.out.println(s1==s2); //false 
   System.out.println(s1.equals(s2)); //true


instanceof operator 
We can use the instance of the operator to check whether the given object is a particular type or not.



Example:
       Object o=l.get(0); // l is an array name 
        if(o instanceof Student) {
                Student s=(Student)o ;
        //perform student specific operation
        }
        else if(o instanceof Customer) {
                Customer c=(Customer)o;
                //perform Customer specific operations
        }

O instanceof X here O is object reference , X is ClassName/Interface name

Example:
        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
        public class Thread extends Object implements Runnable { }



To use instance of operator compulsory there should be some relation between argument types (either child to parent Or parent to child Or same type) Otherwise we will get compile time error saying inconvertible types
Bitwise Operators : ( & , | , ^) 
  • & (AND) : If both arguments are true then only result is true.
  • | (OR) : if at least one argument is true. Then the result is true.
  • ^ (X-OR) : if both are different arguments. Then the result is true.
Example:
    System.out.println(true&false);//false 
    System.out.println(true|false);//true 
    System.out.println(true^false);//true
We can apply bitwise operators even for integral types also.
   
Bitwise Operators : ( & , | , ^)  
Example: 
    System.out.println(4&5);//4           using binary digits
    System.out.println(4|5);//5             4-->100
    System.out.println(4^5);//1             5-->101

Bitwise Operators : ( & , | , ^) 
We can apply this operator only for integral types but not for boolean types.

Example :
       System.out.println(~true); // CE :opetator ~ can not be applied to boolean
       System.out.println(~4); //-5 5.
       description about above program :
       4-->  0 000.......0100      0-----+ve
       ~4--> 1 111.......1011      1--- -ve

 
        2's compliment of ~4 --> 000....0100 add 1 11. 
       result is : 000...0101 =5
Note : 

  • The most significant bit access as sign bit 0 means +ve number , 1 means - ve number.
  • +ve number will be represented directly in memory where as -ve number will be represented in 2's comlement form.               



Boolean complement (!) operator
This operator is applicable only for boolean types but not for integral types.
Example:
       System.out.println(!true);//false 
       System.out.println(!false);//true
       System.out.println(!4);//CE : operator ! can not be applied to int
Summary:     
& | ^   Applicable for both boolean and integral types.
~        Applicable for integral types only but not for boolean types.
!         Applicable for boolean types only but not for integral types.

Short circuit (&&, ||) operators
These operators are exactly same as normal bitwise operators &(AND), |(OR) except the following differences.

& , |
Both arguments should be evaluated always.Relatively performance is low.Applicable for both integral and boolean types.

&& , ||
Second argument evaluation is optional.Relatively performance is high.Applicable only for boolean types but not for integral types.

x&&y 
y will be evaluated if and only if x is true.(If x is false then y won't be evaluated i.e., If x is ture then only y will be evaluated)

x||y 
y will be evaluated if and only if x is false.(If x is true then y won't be evaluated i.e., If x is false then only y will be evaluated)
   
Example :
       int x=10 , y=15 ;
              if(++x < 10 || ++y > 15) { operators
                     x++; 
              }
              else {
                     y++;
              } 
       System.out.println(x+"----"+y);
Output: 
operator  X    Y
&             11   17
|              12   16
&&           11   16
||             12   16 

Type Cast Operator 
There are 2 types of type-casting
  1. Implicit 
  2. explicit

1. implicit type casting

int x='a'; System.out.println(x); //97
  1. The compiler is responsible to perform this type casting.
  2. When ever we are assigning lower datatype value to higher datatype variable then implicit type cast will be performed .
  3. It is also known as Widening or Upcasting.
  4. There is no lose of information in this type casting.
  5. The following are various possible implicit type casting.
Diagram:


Example 1:
    int x='a';
    System.out.println(x);//97
Note: Compiler converts char to int type automatically by implicit type casting.

Example 2:
    double d=10;
    System.out.println(d);//10.0
Note: Compiler converts int to double type automatically by implicit type casting.

2. Explicit type casting

  1. Programmer is responsible for this type casting.
  2. Whenever we are assigning bigger data type value to the smaller data typevariable then explicit type casting is required.
  3. Also known as Narrowing or down casting.
  4. There may be a chance of lose of information in this type casting.
  5. The following are various possible conversions where explicit type casting is
Diagram:


Example1:
  int x=130;
  byte b=(byte)x;
  System.out.println(b); //-126



Example 2:
    int x=130;
    byte b=x;
    System.out.println(b); //CE : possible loss of precision
When ever we are assigning higher datatype value to lower datatype value
variable by explicit type-casting ,the most significant bits will be lost i.e., we have
considered least significant bits.

Example 3:
    int x=150;
    short s=(short)x;
    byte b=(byte)x;
    System.out.println(s); //150
    System.out.println(b); //-106

When ever we are assigning floating point value to the integral types by explicit
type casting , the digits of after decimal point will be lost .

Example 4:
   double d=130.456 ; 30.
   int x=(int)d ;
   System.out.println(x); //130
   byte b=(byte)d ;
   System.out.println(b); //-206
Arithmetic Operator 

There are 3 types of assignment operators

  1. Simple assignment
  2. Chained assignment:
  3. Compound assignment

1. Simple assignment

Example:
    int x=10;

2. Chained assignment

Example 1:

  int a,b,c,d;
  a=b=c=d=20;
  System.out.println(a+"---"+b+"---"+c+"---"+d);//20---20---20---20
  
  int b , c , d ;
  int a=b=c=d=20 ;  //valid
We can't perform chained assignment directly at the time of declaration

Example 2:

   int a=b=c=d=30;
   CE : can not find symbol
   symbol : variable b
   location : class Test

3. Compound assignment

Sometimes we can mixed assignment operator with some other operator to form compound assignment operator.

Example:
  int a=10 ;
  a +=20 ;
  System.out.println(a); //30


The following is the list of all possible compound assignment operators in java.


         















In the case of compound assignment operator internal type casting will be performed automatically by the compiler (similar to increment and decrement operators.)



Example 1:
  byte b=10;
  b=b+1; System.out.println(b);
  CE :possible loss of precission
  found : int
  required : byte
Example 2:
  byte b=10;
  b++; System.out.println(b) //11
Example 3:
  byte b=10;
  b+=1; 
  System.out.println(b); //11
Example 4:
  byte b=127;
  b+=3; 
  System.out.println(b);//-126

Example 5:
  int a , b , c , d ;
  a=b=c=d=20 ;
  a += b-= c *= d /= 2 ; 
  System.out.println(a+"---"+b+"---"+c+"---"+d);// -160...-180---200---10

Conditional Operator (? :)
The only possible ternary operator in java is conditional operator

Example1:
  int x=(10>20)?30:40; 
  System.out.println(x); //40
Example2:
 int x=(10>20)?30:((40>50)?60:70); 
  System.out.println(x); //70    

Nesting of conditional operator is possible

New Operator

  •  We can use "new" operator to create an object
  • There is no "delete" operator in java because destruction of useless objects is the responsibility of garbage collector.

 Java operator precedence:
  1. Unaryoperators:[],x++,x--,++x,--x,~,!,new,<type>
  2. Arithmeticoperators:*,/,%,+,-.
  3. Shiftoperators: >>,>>>,<<.
  4. Comparision operators : <, <=,>,>=, instanceof.
  5. Equality operators: == , !=
  6. Bitwise operators: & , ^ , | .
  7. Short circuit operators: && , || .
  8. Conditional operator: (?:)
  9. Assignmentoperators:+=,-=,*=,/=,%=...
Evaluation order of java operands:
There is no precedence for operands before applying any operator all operands will be evaluated from left to right.

Example1:
 class OperatorsDemo {
      public static void main(String[] args){ 
          System.out.println(m1(1)+m1(2)*m1(3)/m1(4)*m1(5)+m1(6));
      }

     public static int m1(int i) {
         System.out.println(i); return i;
     } 
}
 


        
























Example 2::
  int i=1;
  i+=++i + i++ + ++i + i++; System.out.println(i); //13
description :
  i=i + ++i + i++ + ++i + i++ ; i=1+2+2+4+4;
  i=13;
new Vs newInstance( )

  • new is an operator to create an objects , if we know class name at the beginning then we can create an object by using new operator 
  • newInstance( ) is a method presenting class " Class " , which can be used to create object.
  • If we don't know the class name at the beginning and its available dynamicallyRuntime then we should go for newInstance() method


Example:
public class Test {
      public static void main(String[] args) Throws Exception {
       Object o=Class.forName(arg[0]).newInstance( ) ; 
       System.out.println(o.getClass().getName( ));
      }
 }

  • If dynamically provide class name is not available then we will get the RuntimeException saying ClassNotFoundExceptio
  • To use newInstance( ) method compulsory corresponding class should contains no argument constructor , otherwise we will get the RuntimeException saying InstantiationException.

Difference between new and newInstance()


Difference between ClassNotFoundException & NoClassDefFoundError
For hard coded class names at Runtime in the corresponding .class files not available we will get NoClassDefFoundError , which is unchecked

Example:
      Test t = new Test( );
In Runtime Test.class file is not available then we will get NoClassDefFoundError
For Dynamically provided class names at Runtime , If the corresponding .class files is not available then we will get the RuntimeException saying ClassNotFoundException

Example:
      Object o=Class.forname("Test").newInstance( );

At Runtime if Test.class file not available then we will get the ClassNotFoundException , which is checked exception.
instanceof operator vs isInstance()  
instanceof
  • instanceof an operator which can be used to check whether the given object is perticular type or not.We know at the type at beginning it is available

Example 1:
  String s = new String("ashok"); 
  System.out.println(s instanceof Object );//true
  If we know the type at the beginning only.
Example 2:
  int x= 10 ;
  x=x++; 
  System.out.println(x); //10

isInstance( )

  • isInstance( ) is a method , present in class Class , we can use isInstance( ) method to checked whether the given object is perticular type or not We don't know at the type at beginning it is available Dynamically at Runtime.

Example 1:
class Test {
  public static void main(String[] args) { 
    Test t=newTest(); System.out.println(Class.forName(args[0]).isInstance( ));
    //arg[0] --- We don't know the type at beginning
  } 
 }

java Test Test    //true
java Test String  //false
java  Test Object //true
consider old value of x for assignment x=10
Increment x value x=1
Perform assignment with old considered x value x=10

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS