instanceOf operator

  1. This operator is used to test if an object belongs to the class or not.
  2. Word ‘instance’ means object.
  3. This operator can also be used to check if an object belongs to an interface or not
  4. Example:
    public class Test {
     public static void main(String[] args) {
    	Thread t=new Thread();
    	System.out.println(t instanceof Thread);
    	System.out.println(t instanceof Object);
    	System.out.println(t instanceof Runnable);
     }
    }
    
    

    Output:true
    true
    true

  5. To use ‘instanceof’ operator compulsary there should be some relationship b/n operand types(either parent to child/child to parent/same type)otherwise we will get compile time error saying “inconvertable Types”.
  6. Example:
    public class Test {
     public static void main(String[] args) {
       String s=new String("java2learn");
       System.out.println(s instanceof String);//true
       System.out.println(s instanceof StringBuffer);//C.E
       //inconvertible types
     }
    }
    
    

    Example:

    public class Test {
     public static void main(String[] args) {
    	Object o=new Object();
    	System.out.println(o instanceof String);
     }
    }
    /*
    Output:
    false
    */
    

    Note:
    For any class or interface X (null instanceof X) is always false

new operator

This operator can be used for creating objects.Objects are created on heap memory by JVM. There is no delete operator in java,Garbage collector is responsible for deleting the objects.

Syntax:
classname obj=new Classname();

Example:

import java.lang.*;
public class Test {
 public static void main(String[] args) {
  Object o=new Object();   //o is an object of the Objectclass
 }
}