The instanceof keyword in java which is used to test if an object is of a specified type.The general form of instanceof Keyword is
"object instanceof type"
Here, the object is an instance of a class, and type is a class type. If object is of the specified type or can be cast into the specified type, then the instanceof Keyword evaluates to true. Otherwise, it evaluates false.It is the means by which your program can obtain run-time type information about an object.
Example:
public class test {
public static void main(String[] b) {
String temp = "Hello";
if (temp instanceof java.lang.String) {
System.out.println("yes it's true");
}else {
System.out.println("Oops it's false");
}
}
}
However, above example returns yes it's true.Because String temp is instanceof of java.lang.String.
if you declare String temp=null means it returns Oops it's false.Because applying instanceof on a null reference variable returns false
Another Example is
class A {
public A() {
}
}
class B extends A {
public B() {
super();
}
}
public class MainClass {
public static void main(String[] test) {
B b= new B();
if (b instanceof A) {
System.out.println("true");
}
}
}
it returns true.Because class B is instanceof of A.
"object instanceof type"
Here, the object is an instance of a class, and type is a class type. If object is of the specified type or can be cast into the specified type, then the instanceof Keyword evaluates to true. Otherwise, it evaluates false.It is the means by which your program can obtain run-time type information about an object.
Example:
public class test {
public static void main(String[] b) {
String temp = "Hello";
if (temp instanceof java.lang.String) {
System.out.println("yes it's true");
}else {
System.out.println("Oops it's false");
}
}
}
However, above example returns yes it's true.Because String temp is instanceof of java.lang.String.
if you declare String temp=null means it returns Oops it's false.Because applying instanceof on a null reference variable returns false
Another Example is
class A {
public A() {
}
}
class B extends A {
public B() {
super();
}
}
public class MainClass {
public static void main(String[] test) {
B b= new B();
if (b instanceof A) {
System.out.println("true");
}
}
}
it returns true.Because class B is instanceof of A.
No comments:
Post a Comment