Sponsored Links
Ad by Google
The instanceof operator also known as type comparison operator, and it's very useful to compare the type of object. It compares an object to a specified type. One can use instanceof operator to test if an object is an instance of class,sub-class or interface, just like checking of serializable interface after implementation of serializable.
In this post, I am going to show you few examples of how to use instanceof operator in your code.
Example 1:
We know that, String class by default implement the Serializable interface,lets check this.
String by default implement Serializable
Example 2:
parent is parent => true
child is child => true
Example 3:
null is not an instance of anything, so comparison with null, it should return false.
false
In this post, I am going to show you few examples of how to use instanceof operator in your code.
Example 1:
We know that, String class by default implement the Serializable interface,lets check this.
package com.javamakeuse.poc.bd; import java.io.Serializable; public class InstanceOfOp { public static void main(String[] args) { String str = "implemented serializable"; if (str instanceof Serializable) { System.out.println("String by default implement Serializable"); } } }Output:
String by default implement Serializable
Example 2:
package com.javamakeuse.poc.bd; public class InstanceOfOp { public static void main(String[] args) { Parent parent = new Parent(); Parent child = new Child(); System.out.println("parent is parent => " + (parent instanceof Parent)); System.out.println("child is child => " + (child instanceof Parent)); } } class Parent { } class Child extends Parent { }Output:
parent is parent => true
child is child => true
Example 3:
null is not an instance of anything, so comparison with null, it should return false.
package com.javamakeuse.poc.bd; public class InstanceOfOp { public static void main(String[] args) { String str = null; System.out.println(str instanceof String); } }Output:
false
Sponsored Links
0 comments:
Post a Comment