What is the 'instanceof' operator used for in Java?
up vote
142
down vote
favorite
What is the instanceof
operator used for? I've seen stuff like
if (source instanceof Button) {
//...
} else {
//...
}
But none of it made sense to me. I've done my research, but came up only with examples without any explanations.
java instanceof
|
show 1 more comment
up vote
142
down vote
favorite
What is the instanceof
operator used for? I've seen stuff like
if (source instanceof Button) {
//...
} else {
//...
}
But none of it made sense to me. I've done my research, but came up only with examples without any explanations.
java instanceof
31
There is nothing wrong with asking questions here, but if you are learning Java you might want to get a book. Any decent Java book would have the answer to this question and the next 1000 you're going to have.
– James K Polk
Sep 5 '11 at 23:32
Such an operator has many specific uses. This would be a specific question if it asked for an explanation of one of the examples that did not make sense to you.
– Raedwald
Aug 23 '13 at 7:15
1
The answers below are correct, however note that instanceof is an overused operator 9 times out of 10 it can be replaced by a proper use of polymorphism (not always, but often)
– Richard Tingle
Aug 24 '13 at 18:22
I'd go one further than Richard: I have NEVER seen a valid use of instanceof. It's only useful for quick hacks on top of poorly designed code. If you don't like OOP, write in another language (there are plenty). Just say, "no" to instanceof!
– Scott Biggs
Nov 27 '15 at 22:14
4
@ScottBiggs Is there a good alternative toinstanceof
when overridingequals
?
– Ben Aaronson
Sep 7 '16 at 14:55
|
show 1 more comment
up vote
142
down vote
favorite
up vote
142
down vote
favorite
What is the instanceof
operator used for? I've seen stuff like
if (source instanceof Button) {
//...
} else {
//...
}
But none of it made sense to me. I've done my research, but came up only with examples without any explanations.
java instanceof
What is the instanceof
operator used for? I've seen stuff like
if (source instanceof Button) {
//...
} else {
//...
}
But none of it made sense to me. I've done my research, but came up only with examples without any explanations.
java instanceof
java instanceof
edited Aug 13 '17 at 4:23
Pacerier
43.5k50210513
43.5k50210513
asked Sep 5 '11 at 23:28
Ben
717263
717263
31
There is nothing wrong with asking questions here, but if you are learning Java you might want to get a book. Any decent Java book would have the answer to this question and the next 1000 you're going to have.
– James K Polk
Sep 5 '11 at 23:32
Such an operator has many specific uses. This would be a specific question if it asked for an explanation of one of the examples that did not make sense to you.
– Raedwald
Aug 23 '13 at 7:15
1
The answers below are correct, however note that instanceof is an overused operator 9 times out of 10 it can be replaced by a proper use of polymorphism (not always, but often)
– Richard Tingle
Aug 24 '13 at 18:22
I'd go one further than Richard: I have NEVER seen a valid use of instanceof. It's only useful for quick hacks on top of poorly designed code. If you don't like OOP, write in another language (there are plenty). Just say, "no" to instanceof!
– Scott Biggs
Nov 27 '15 at 22:14
4
@ScottBiggs Is there a good alternative toinstanceof
when overridingequals
?
– Ben Aaronson
Sep 7 '16 at 14:55
|
show 1 more comment
31
There is nothing wrong with asking questions here, but if you are learning Java you might want to get a book. Any decent Java book would have the answer to this question and the next 1000 you're going to have.
– James K Polk
Sep 5 '11 at 23:32
Such an operator has many specific uses. This would be a specific question if it asked for an explanation of one of the examples that did not make sense to you.
– Raedwald
Aug 23 '13 at 7:15
1
The answers below are correct, however note that instanceof is an overused operator 9 times out of 10 it can be replaced by a proper use of polymorphism (not always, but often)
– Richard Tingle
Aug 24 '13 at 18:22
I'd go one further than Richard: I have NEVER seen a valid use of instanceof. It's only useful for quick hacks on top of poorly designed code. If you don't like OOP, write in another language (there are plenty). Just say, "no" to instanceof!
– Scott Biggs
Nov 27 '15 at 22:14
4
@ScottBiggs Is there a good alternative toinstanceof
when overridingequals
?
– Ben Aaronson
Sep 7 '16 at 14:55
31
31
There is nothing wrong with asking questions here, but if you are learning Java you might want to get a book. Any decent Java book would have the answer to this question and the next 1000 you're going to have.
– James K Polk
Sep 5 '11 at 23:32
There is nothing wrong with asking questions here, but if you are learning Java you might want to get a book. Any decent Java book would have the answer to this question and the next 1000 you're going to have.
– James K Polk
Sep 5 '11 at 23:32
Such an operator has many specific uses. This would be a specific question if it asked for an explanation of one of the examples that did not make sense to you.
– Raedwald
Aug 23 '13 at 7:15
Such an operator has many specific uses. This would be a specific question if it asked for an explanation of one of the examples that did not make sense to you.
– Raedwald
Aug 23 '13 at 7:15
1
1
The answers below are correct, however note that instanceof is an overused operator 9 times out of 10 it can be replaced by a proper use of polymorphism (not always, but often)
– Richard Tingle
Aug 24 '13 at 18:22
The answers below are correct, however note that instanceof is an overused operator 9 times out of 10 it can be replaced by a proper use of polymorphism (not always, but often)
– Richard Tingle
Aug 24 '13 at 18:22
I'd go one further than Richard: I have NEVER seen a valid use of instanceof. It's only useful for quick hacks on top of poorly designed code. If you don't like OOP, write in another language (there are plenty). Just say, "no" to instanceof!
– Scott Biggs
Nov 27 '15 at 22:14
I'd go one further than Richard: I have NEVER seen a valid use of instanceof. It's only useful for quick hacks on top of poorly designed code. If you don't like OOP, write in another language (there are plenty). Just say, "no" to instanceof!
– Scott Biggs
Nov 27 '15 at 22:14
4
4
@ScottBiggs Is there a good alternative to
instanceof
when overriding equals
?– Ben Aaronson
Sep 7 '16 at 14:55
@ScottBiggs Is there a good alternative to
instanceof
when overriding equals
?– Ben Aaronson
Sep 7 '16 at 14:55
|
show 1 more comment
15 Answers
15
active
oldest
votes
up vote
209
down vote
instanceof
keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.
Imagine:
interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}
Imagine a dog
object, created with Object dog = new Dog()
, then:
dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal // true - Dog extends Animal
dog instanceof Dog // true - Dog is Dog
dog instanceof Object // true - Object is the parent type of all objects
However, with Object animal = new Animal();
,
animal instanceof Dog // false
because Animal
is a supertype of Dog
and possibly less "refined".
And,
dog instanceof Cat // does not even compile!
This is because Dog
is neither a subtype nor a supertype of Cat
, and it also does not implement it.
Note that the variable used for dog
above is of type Object
. This is to show instanceof
is a runtime operation and brings us to a/the use case: to react differently based upon an objects type at runtime.
Things to note: expressionThatIsNull instanceof T
is false for all Types T
.
Happy coding.
13
I just tried -Object dog = new Dog(); System.out.println(dog instanceof Cat);
. This compiles just fine and printsfalse
. The compiler is not allowed to determine at compile time thatdog
cannot be a Cat (per the rules in the JLS)
– Erwin Bolwidt
Oct 3 '16 at 13:15
@ErwinBolwidt You made a mistake when you tried that. For anyone wondering: JLS Section 15.20.2 is the one you are looking for. For a minimal nonworking example:boolean b = "foo" instanceof Integer;
– Felix S
Aug 7 '17 at 8:04
2
@FelixS You need to read the answer again. The answer is aboutObject indirect = ...; if (indirect instanceof Something)
. It's not aboutif (literal instanceof Something)
like you seem to be assuming.
– Erwin Bolwidt
Aug 7 '17 at 9:32
@ErwinBolwidt Oh, right, I must have skipped over theObject dog
part. My bad!
– Felix S
Aug 8 '17 at 10:21
add a comment |
up vote
40
down vote
It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.
Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).
instanceof
is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.
if (obj instanceof Checkbox)
{
Checkbox cb = (Checkbox)obj;
boolean state = cb.getState();
}
14
That is to say, usinginstanceof
can make it safe to downcast.
– Raedwald
Aug 23 '13 at 7:11
add a comment |
up vote
27
down vote
As described on this site:
The
instanceof
operator can be used to test if an object is of a
specific type...
if (objectReference instanceof type)
A quick example:
String s = "Hello World!"
return s instanceof String;
//result --> true
However, applying
instanceof
on a null reference variable/expression
returns false.
String s = null;
return s instanceof String;
//result --> false
Since a subclass is a 'type' of its superclass, you can use the
instanceof
to verify this...
class Parent {
public Parent() {}
}
class Child extends Parent {
public Child() {
super();
}
}
public class Main {
public static void main(String args) {
Child child = new Child();
System.out.println( child instanceof Parent );
}
}
//result --> true
I hope this helps!
add a comment |
up vote
14
down vote
If source
is an object
variable, instanceof
is a way of checking to see if it is a Button
or not.
add a comment |
up vote
14
down vote
This operator allows you to determine the type of an object.
It returns a boolean
value.
For example
package test;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
public class instanceoftest
{
public static void main(String args)
{
Map m=new HashMap();
System.out.println("Returns a boolean value "+(m instanceof Map));
System.out.println("Returns a boolean value "+(m instanceof HashMap));
System.out.println("Returns a boolean value "+(m instanceof Object));
System.out.println("Returns a boolean value "+(m instanceof Date));
}
}
the output is:
Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false
add a comment |
up vote
3
down vote
As mentioned in other answers, the canonical typical usage of instanceof
is for checking if an identifier is referring to a more specific type. Example:
Object someobject = ... some code which gets something that might be a button ...
if (someobject instanceof Button) {
// then if someobject is in fact a button this block gets executed
} else {
// otherwise execute this block
}
Note however, that the type of the left-hand expression must be a parent type of the right hand expression (see JLS 15.20.2 and Java Puzzlers, #50, pp114). For example, the following will fail to compile:
public class Test {
public static void main(String args) {
System.out.println(new Test() instanceof String); // will fail to compile
}
}
This fails to compile with the message:
Test.java:6: error: inconvertible types
System.out.println(t instanceof String);
^
required: String
found: Test
1 error
As Test
is not a parent class of String
. OTOH, this compiles perfectly and prints false
as expected:
public class Test {
public static void main(String args) {
Object t = new Test();
// compiles fine since Object is a parent class to String
System.out.println(t instanceof String);
}
}
Thanks for linking to the spec!
– jpaugh
Jan 28 '16 at 19:26
add a comment |
up vote
1
down vote
public class Animal{ float age; }
public class Lion extends Animal { int claws;}
public class Jungle {
public static void main(String args) {
Animal animal = new Animal();
Animal animal2 = new Lion();
Lion lion = new Lion();
Animal animal3 = new Animal();
Lion lion2 = new Animal(); //won't compile (can't reference super class object with sub class reference variable)
if(animal instanceof Lion) //false
if(animal2 instanceof Lion) //true
if(lion insanceof Lion) //true
if(animal3 instanceof Animal) //true
}
}
add a comment |
up vote
1
down vote
Can be used as a shorthand in equality check.
So this code
if(ob != null && this.getClass() == ob.getClass) {
}
Can be written as
if(ob instanceOf ClassA) {
}
add a comment |
up vote
0
down vote
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
add a comment |
up vote
0
down vote
Instance of keyword is helpful when you want to know particular object's instance .
Suppose you are throw exception and when you have catch then perform sum custom operation and then again continue as per your logic (throws or log etc)
Example :
1) User created custom exception "InvalidExtensionsException" and throw it as per logic
2) Now in catch block
catch (Exception e) {
perform sum logic if exception type is "InvalidExtensionsException"
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
3) If you are not checking instance of and exception type is Null pointer exception your code will break.
So your logic should be inside of instance of
if (e instanceof InvalidExtensionsException){
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
}
Above example is wrong coding practice However this example is help you to understand use of instance of it.
add a comment |
up vote
0
down vote
Most people have correctly explained the "What" of this question but no one explained "How" correctly.
So here's a simple illustration:
String s = new String("Hello");
if (s instanceof String) System.out.println("s is instance of String"); // True
if (s instanceof Object) System.out.println("s is instance of Object"); // True
//if (s instanceof StringBuffer) System.out.println("s is instance of StringBuffer"); // Compile error
Object o = (Object)s;
if (o instanceof StringBuffer) System.out.println("o is instance of StringBuffer"); //No error, returns False
else System.out.println("Not an instance of StringBuffer"); //
if (o instanceof String) System.out.println("o is instance of String"); //True
Outputs:
s is instance of String
s is instance of Object
Not an instance of StringBuffer
o is instance of String
The reason for compiler error when comparing s
with StringBuffer is well explained in docs:
You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
which implies the LHS must either be an instance of RHS or of a Class that either implements RHS or extends RHS.
How to use use instanceof then?
Since every Class extends Object, type-casting LHS to object will always work in your favour:
String s = new String("Hello");
if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //No compiler error now :)
else System.out.println("Not an instance of StringBuffer");
Outputs:
Not an instance of StringBuffer
In the last example, why is it returning "Not an instance of StringBuffer"? Since you typecasted s to Object on LHS and checking if it is an instanceof RHS,if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //shouldn't this be true
, since we are typecasting s to Object?
– sofs1
Sep 12 at 5:17
Because s is a reference to String object (Java employs dynamic polymorphism unlike C++) and String isn't a subclass of StringBuffer.
– sziraqui
Sep 13 at 10:18
add a comment |
up vote
-1
down vote
You could use Map to make higher abstraction on instance of
private final Map<Class, Consumer<String>> actions = new HashMap<>();
Then having such map add some action to it:
actions.put(String.class, new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("action for String");
}
};
Then having an Object of not known type you could get specific action from that map:
actions.get(someObject).accept(someObject)
add a comment |
up vote
-1
down vote
class Test48{
public static void main (String args){
Object Obj=new Hello();
//Hello obj=new Hello;
System.out.println(Obj instanceof String);
System.out.println(Obj instanceof Hello);
System.out.println(Obj instanceof Object);
Hello h=null;
System.out.println(h instanceof Hello);
System.out.println(h instanceof Object);
}
}
Don't post code only answers on StackOverflow. Please go ahead and add an explaination.
– L. Guthardt
Jul 9 at 6:44
add a comment |
up vote
-2
down vote
Very simple code example:
If (object1 instanceof Class1) {
// do something
} else if (object1 instanceof Class2) {
// do something different
}
Be careful here. In the example above, if Class1 is Object, the first comparison will always be true. So, just like with exceptions, hierarchical order matters!
add a comment |
up vote
-2
down vote
The instanceof operator is used to check whether the object is an instance of the specified type. (class or subclass or interface).
The instanceof is also known as type comparison operator because it compares the instance with type. It returns either true or false.
class Simple1 {
public static void main(String args) {
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1); //true
}
}
If we apply the instanceof operator with any variable that has null value, it returns false.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7313559%2fwhat-is-the-instanceof-operator-used-for-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
209
down vote
instanceof
keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.
Imagine:
interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}
Imagine a dog
object, created with Object dog = new Dog()
, then:
dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal // true - Dog extends Animal
dog instanceof Dog // true - Dog is Dog
dog instanceof Object // true - Object is the parent type of all objects
However, with Object animal = new Animal();
,
animal instanceof Dog // false
because Animal
is a supertype of Dog
and possibly less "refined".
And,
dog instanceof Cat // does not even compile!
This is because Dog
is neither a subtype nor a supertype of Cat
, and it also does not implement it.
Note that the variable used for dog
above is of type Object
. This is to show instanceof
is a runtime operation and brings us to a/the use case: to react differently based upon an objects type at runtime.
Things to note: expressionThatIsNull instanceof T
is false for all Types T
.
Happy coding.
13
I just tried -Object dog = new Dog(); System.out.println(dog instanceof Cat);
. This compiles just fine and printsfalse
. The compiler is not allowed to determine at compile time thatdog
cannot be a Cat (per the rules in the JLS)
– Erwin Bolwidt
Oct 3 '16 at 13:15
@ErwinBolwidt You made a mistake when you tried that. For anyone wondering: JLS Section 15.20.2 is the one you are looking for. For a minimal nonworking example:boolean b = "foo" instanceof Integer;
– Felix S
Aug 7 '17 at 8:04
2
@FelixS You need to read the answer again. The answer is aboutObject indirect = ...; if (indirect instanceof Something)
. It's not aboutif (literal instanceof Something)
like you seem to be assuming.
– Erwin Bolwidt
Aug 7 '17 at 9:32
@ErwinBolwidt Oh, right, I must have skipped over theObject dog
part. My bad!
– Felix S
Aug 8 '17 at 10:21
add a comment |
up vote
209
down vote
instanceof
keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.
Imagine:
interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}
Imagine a dog
object, created with Object dog = new Dog()
, then:
dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal // true - Dog extends Animal
dog instanceof Dog // true - Dog is Dog
dog instanceof Object // true - Object is the parent type of all objects
However, with Object animal = new Animal();
,
animal instanceof Dog // false
because Animal
is a supertype of Dog
and possibly less "refined".
And,
dog instanceof Cat // does not even compile!
This is because Dog
is neither a subtype nor a supertype of Cat
, and it also does not implement it.
Note that the variable used for dog
above is of type Object
. This is to show instanceof
is a runtime operation and brings us to a/the use case: to react differently based upon an objects type at runtime.
Things to note: expressionThatIsNull instanceof T
is false for all Types T
.
Happy coding.
13
I just tried -Object dog = new Dog(); System.out.println(dog instanceof Cat);
. This compiles just fine and printsfalse
. The compiler is not allowed to determine at compile time thatdog
cannot be a Cat (per the rules in the JLS)
– Erwin Bolwidt
Oct 3 '16 at 13:15
@ErwinBolwidt You made a mistake when you tried that. For anyone wondering: JLS Section 15.20.2 is the one you are looking for. For a minimal nonworking example:boolean b = "foo" instanceof Integer;
– Felix S
Aug 7 '17 at 8:04
2
@FelixS You need to read the answer again. The answer is aboutObject indirect = ...; if (indirect instanceof Something)
. It's not aboutif (literal instanceof Something)
like you seem to be assuming.
– Erwin Bolwidt
Aug 7 '17 at 9:32
@ErwinBolwidt Oh, right, I must have skipped over theObject dog
part. My bad!
– Felix S
Aug 8 '17 at 10:21
add a comment |
up vote
209
down vote
up vote
209
down vote
instanceof
keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.
Imagine:
interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}
Imagine a dog
object, created with Object dog = new Dog()
, then:
dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal // true - Dog extends Animal
dog instanceof Dog // true - Dog is Dog
dog instanceof Object // true - Object is the parent type of all objects
However, with Object animal = new Animal();
,
animal instanceof Dog // false
because Animal
is a supertype of Dog
and possibly less "refined".
And,
dog instanceof Cat // does not even compile!
This is because Dog
is neither a subtype nor a supertype of Cat
, and it also does not implement it.
Note that the variable used for dog
above is of type Object
. This is to show instanceof
is a runtime operation and brings us to a/the use case: to react differently based upon an objects type at runtime.
Things to note: expressionThatIsNull instanceof T
is false for all Types T
.
Happy coding.
instanceof
keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.
Imagine:
interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}
Imagine a dog
object, created with Object dog = new Dog()
, then:
dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal // true - Dog extends Animal
dog instanceof Dog // true - Dog is Dog
dog instanceof Object // true - Object is the parent type of all objects
However, with Object animal = new Animal();
,
animal instanceof Dog // false
because Animal
is a supertype of Dog
and possibly less "refined".
And,
dog instanceof Cat // does not even compile!
This is because Dog
is neither a subtype nor a supertype of Cat
, and it also does not implement it.
Note that the variable used for dog
above is of type Object
. This is to show instanceof
is a runtime operation and brings us to a/the use case: to react differently based upon an objects type at runtime.
Things to note: expressionThatIsNull instanceof T
is false for all Types T
.
Happy coding.
edited Mar 6 '17 at 1:09
Cache Staheli
1,87452234
1,87452234
answered Sep 5 '11 at 23:37
user166390
13
I just tried -Object dog = new Dog(); System.out.println(dog instanceof Cat);
. This compiles just fine and printsfalse
. The compiler is not allowed to determine at compile time thatdog
cannot be a Cat (per the rules in the JLS)
– Erwin Bolwidt
Oct 3 '16 at 13:15
@ErwinBolwidt You made a mistake when you tried that. For anyone wondering: JLS Section 15.20.2 is the one you are looking for. For a minimal nonworking example:boolean b = "foo" instanceof Integer;
– Felix S
Aug 7 '17 at 8:04
2
@FelixS You need to read the answer again. The answer is aboutObject indirect = ...; if (indirect instanceof Something)
. It's not aboutif (literal instanceof Something)
like you seem to be assuming.
– Erwin Bolwidt
Aug 7 '17 at 9:32
@ErwinBolwidt Oh, right, I must have skipped over theObject dog
part. My bad!
– Felix S
Aug 8 '17 at 10:21
add a comment |
13
I just tried -Object dog = new Dog(); System.out.println(dog instanceof Cat);
. This compiles just fine and printsfalse
. The compiler is not allowed to determine at compile time thatdog
cannot be a Cat (per the rules in the JLS)
– Erwin Bolwidt
Oct 3 '16 at 13:15
@ErwinBolwidt You made a mistake when you tried that. For anyone wondering: JLS Section 15.20.2 is the one you are looking for. For a minimal nonworking example:boolean b = "foo" instanceof Integer;
– Felix S
Aug 7 '17 at 8:04
2
@FelixS You need to read the answer again. The answer is aboutObject indirect = ...; if (indirect instanceof Something)
. It's not aboutif (literal instanceof Something)
like you seem to be assuming.
– Erwin Bolwidt
Aug 7 '17 at 9:32
@ErwinBolwidt Oh, right, I must have skipped over theObject dog
part. My bad!
– Felix S
Aug 8 '17 at 10:21
13
13
I just tried -
Object dog = new Dog(); System.out.println(dog instanceof Cat);
. This compiles just fine and prints false
. The compiler is not allowed to determine at compile time that dog
cannot be a Cat (per the rules in the JLS)– Erwin Bolwidt
Oct 3 '16 at 13:15
I just tried -
Object dog = new Dog(); System.out.println(dog instanceof Cat);
. This compiles just fine and prints false
. The compiler is not allowed to determine at compile time that dog
cannot be a Cat (per the rules in the JLS)– Erwin Bolwidt
Oct 3 '16 at 13:15
@ErwinBolwidt You made a mistake when you tried that. For anyone wondering: JLS Section 15.20.2 is the one you are looking for. For a minimal nonworking example:
boolean b = "foo" instanceof Integer;
– Felix S
Aug 7 '17 at 8:04
@ErwinBolwidt You made a mistake when you tried that. For anyone wondering: JLS Section 15.20.2 is the one you are looking for. For a minimal nonworking example:
boolean b = "foo" instanceof Integer;
– Felix S
Aug 7 '17 at 8:04
2
2
@FelixS You need to read the answer again. The answer is about
Object indirect = ...; if (indirect instanceof Something)
. It's not about if (literal instanceof Something)
like you seem to be assuming.– Erwin Bolwidt
Aug 7 '17 at 9:32
@FelixS You need to read the answer again. The answer is about
Object indirect = ...; if (indirect instanceof Something)
. It's not about if (literal instanceof Something)
like you seem to be assuming.– Erwin Bolwidt
Aug 7 '17 at 9:32
@ErwinBolwidt Oh, right, I must have skipped over the
Object dog
part. My bad!– Felix S
Aug 8 '17 at 10:21
@ErwinBolwidt Oh, right, I must have skipped over the
Object dog
part. My bad!– Felix S
Aug 8 '17 at 10:21
add a comment |
up vote
40
down vote
It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.
Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).
instanceof
is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.
if (obj instanceof Checkbox)
{
Checkbox cb = (Checkbox)obj;
boolean state = cb.getState();
}
14
That is to say, usinginstanceof
can make it safe to downcast.
– Raedwald
Aug 23 '13 at 7:11
add a comment |
up vote
40
down vote
It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.
Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).
instanceof
is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.
if (obj instanceof Checkbox)
{
Checkbox cb = (Checkbox)obj;
boolean state = cb.getState();
}
14
That is to say, usinginstanceof
can make it safe to downcast.
– Raedwald
Aug 23 '13 at 7:11
add a comment |
up vote
40
down vote
up vote
40
down vote
It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.
Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).
instanceof
is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.
if (obj instanceof Checkbox)
{
Checkbox cb = (Checkbox)obj;
boolean state = cb.getState();
}
It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.
Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).
instanceof
is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.
if (obj instanceof Checkbox)
{
Checkbox cb = (Checkbox)obj;
boolean state = cb.getState();
}
edited Sep 5 '11 at 23:37
answered Sep 5 '11 at 23:31
Michael Petrotta
51.3k12127170
51.3k12127170
14
That is to say, usinginstanceof
can make it safe to downcast.
– Raedwald
Aug 23 '13 at 7:11
add a comment |
14
That is to say, usinginstanceof
can make it safe to downcast.
– Raedwald
Aug 23 '13 at 7:11
14
14
That is to say, using
instanceof
can make it safe to downcast.– Raedwald
Aug 23 '13 at 7:11
That is to say, using
instanceof
can make it safe to downcast.– Raedwald
Aug 23 '13 at 7:11
add a comment |
up vote
27
down vote
As described on this site:
The
instanceof
operator can be used to test if an object is of a
specific type...
if (objectReference instanceof type)
A quick example:
String s = "Hello World!"
return s instanceof String;
//result --> true
However, applying
instanceof
on a null reference variable/expression
returns false.
String s = null;
return s instanceof String;
//result --> false
Since a subclass is a 'type' of its superclass, you can use the
instanceof
to verify this...
class Parent {
public Parent() {}
}
class Child extends Parent {
public Child() {
super();
}
}
public class Main {
public static void main(String args) {
Child child = new Child();
System.out.println( child instanceof Parent );
}
}
//result --> true
I hope this helps!
add a comment |
up vote
27
down vote
As described on this site:
The
instanceof
operator can be used to test if an object is of a
specific type...
if (objectReference instanceof type)
A quick example:
String s = "Hello World!"
return s instanceof String;
//result --> true
However, applying
instanceof
on a null reference variable/expression
returns false.
String s = null;
return s instanceof String;
//result --> false
Since a subclass is a 'type' of its superclass, you can use the
instanceof
to verify this...
class Parent {
public Parent() {}
}
class Child extends Parent {
public Child() {
super();
}
}
public class Main {
public static void main(String args) {
Child child = new Child();
System.out.println( child instanceof Parent );
}
}
//result --> true
I hope this helps!
add a comment |
up vote
27
down vote
up vote
27
down vote
As described on this site:
The
instanceof
operator can be used to test if an object is of a
specific type...
if (objectReference instanceof type)
A quick example:
String s = "Hello World!"
return s instanceof String;
//result --> true
However, applying
instanceof
on a null reference variable/expression
returns false.
String s = null;
return s instanceof String;
//result --> false
Since a subclass is a 'type' of its superclass, you can use the
instanceof
to verify this...
class Parent {
public Parent() {}
}
class Child extends Parent {
public Child() {
super();
}
}
public class Main {
public static void main(String args) {
Child child = new Child();
System.out.println( child instanceof Parent );
}
}
//result --> true
I hope this helps!
As described on this site:
The
instanceof
operator can be used to test if an object is of a
specific type...
if (objectReference instanceof type)
A quick example:
String s = "Hello World!"
return s instanceof String;
//result --> true
However, applying
instanceof
on a null reference variable/expression
returns false.
String s = null;
return s instanceof String;
//result --> false
Since a subclass is a 'type' of its superclass, you can use the
instanceof
to verify this...
class Parent {
public Parent() {}
}
class Child extends Parent {
public Child() {
super();
}
}
public class Main {
public static void main(String args) {
Child child = new Child();
System.out.println( child instanceof Parent );
}
}
//result --> true
I hope this helps!
edited Apr 4 at 11:08
Shantaram Tupe
1,2002925
1,2002925
answered Sep 5 '11 at 23:33
fireshadow52
4,90721936
4,90721936
add a comment |
add a comment |
up vote
14
down vote
If source
is an object
variable, instanceof
is a way of checking to see if it is a Button
or not.
add a comment |
up vote
14
down vote
If source
is an object
variable, instanceof
is a way of checking to see if it is a Button
or not.
add a comment |
up vote
14
down vote
up vote
14
down vote
If source
is an object
variable, instanceof
is a way of checking to see if it is a Button
or not.
If source
is an object
variable, instanceof
is a way of checking to see if it is a Button
or not.
answered Sep 5 '11 at 23:29
Daniel A. White
147k36292372
147k36292372
add a comment |
add a comment |
up vote
14
down vote
This operator allows you to determine the type of an object.
It returns a boolean
value.
For example
package test;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
public class instanceoftest
{
public static void main(String args)
{
Map m=new HashMap();
System.out.println("Returns a boolean value "+(m instanceof Map));
System.out.println("Returns a boolean value "+(m instanceof HashMap));
System.out.println("Returns a boolean value "+(m instanceof Object));
System.out.println("Returns a boolean value "+(m instanceof Date));
}
}
the output is:
Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false
add a comment |
up vote
14
down vote
This operator allows you to determine the type of an object.
It returns a boolean
value.
For example
package test;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
public class instanceoftest
{
public static void main(String args)
{
Map m=new HashMap();
System.out.println("Returns a boolean value "+(m instanceof Map));
System.out.println("Returns a boolean value "+(m instanceof HashMap));
System.out.println("Returns a boolean value "+(m instanceof Object));
System.out.println("Returns a boolean value "+(m instanceof Date));
}
}
the output is:
Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false
add a comment |
up vote
14
down vote
up vote
14
down vote
This operator allows you to determine the type of an object.
It returns a boolean
value.
For example
package test;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
public class instanceoftest
{
public static void main(String args)
{
Map m=new HashMap();
System.out.println("Returns a boolean value "+(m instanceof Map));
System.out.println("Returns a boolean value "+(m instanceof HashMap));
System.out.println("Returns a boolean value "+(m instanceof Object));
System.out.println("Returns a boolean value "+(m instanceof Date));
}
}
the output is:
Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false
This operator allows you to determine the type of an object.
It returns a boolean
value.
For example
package test;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
public class instanceoftest
{
public static void main(String args)
{
Map m=new HashMap();
System.out.println("Returns a boolean value "+(m instanceof Map));
System.out.println("Returns a boolean value "+(m instanceof HashMap));
System.out.println("Returns a boolean value "+(m instanceof Object));
System.out.println("Returns a boolean value "+(m instanceof Date));
}
}
the output is:
Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false
edited Aug 3 '16 at 13:41
River
5,26183351
5,26183351
answered May 8 '14 at 14:55
Purendra Agrawal
430616
430616
add a comment |
add a comment |
up vote
3
down vote
As mentioned in other answers, the canonical typical usage of instanceof
is for checking if an identifier is referring to a more specific type. Example:
Object someobject = ... some code which gets something that might be a button ...
if (someobject instanceof Button) {
// then if someobject is in fact a button this block gets executed
} else {
// otherwise execute this block
}
Note however, that the type of the left-hand expression must be a parent type of the right hand expression (see JLS 15.20.2 and Java Puzzlers, #50, pp114). For example, the following will fail to compile:
public class Test {
public static void main(String args) {
System.out.println(new Test() instanceof String); // will fail to compile
}
}
This fails to compile with the message:
Test.java:6: error: inconvertible types
System.out.println(t instanceof String);
^
required: String
found: Test
1 error
As Test
is not a parent class of String
. OTOH, this compiles perfectly and prints false
as expected:
public class Test {
public static void main(String args) {
Object t = new Test();
// compiles fine since Object is a parent class to String
System.out.println(t instanceof String);
}
}
Thanks for linking to the spec!
– jpaugh
Jan 28 '16 at 19:26
add a comment |
up vote
3
down vote
As mentioned in other answers, the canonical typical usage of instanceof
is for checking if an identifier is referring to a more specific type. Example:
Object someobject = ... some code which gets something that might be a button ...
if (someobject instanceof Button) {
// then if someobject is in fact a button this block gets executed
} else {
// otherwise execute this block
}
Note however, that the type of the left-hand expression must be a parent type of the right hand expression (see JLS 15.20.2 and Java Puzzlers, #50, pp114). For example, the following will fail to compile:
public class Test {
public static void main(String args) {
System.out.println(new Test() instanceof String); // will fail to compile
}
}
This fails to compile with the message:
Test.java:6: error: inconvertible types
System.out.println(t instanceof String);
^
required: String
found: Test
1 error
As Test
is not a parent class of String
. OTOH, this compiles perfectly and prints false
as expected:
public class Test {
public static void main(String args) {
Object t = new Test();
// compiles fine since Object is a parent class to String
System.out.println(t instanceof String);
}
}
Thanks for linking to the spec!
– jpaugh
Jan 28 '16 at 19:26
add a comment |
up vote
3
down vote
up vote
3
down vote
As mentioned in other answers, the canonical typical usage of instanceof
is for checking if an identifier is referring to a more specific type. Example:
Object someobject = ... some code which gets something that might be a button ...
if (someobject instanceof Button) {
// then if someobject is in fact a button this block gets executed
} else {
// otherwise execute this block
}
Note however, that the type of the left-hand expression must be a parent type of the right hand expression (see JLS 15.20.2 and Java Puzzlers, #50, pp114). For example, the following will fail to compile:
public class Test {
public static void main(String args) {
System.out.println(new Test() instanceof String); // will fail to compile
}
}
This fails to compile with the message:
Test.java:6: error: inconvertible types
System.out.println(t instanceof String);
^
required: String
found: Test
1 error
As Test
is not a parent class of String
. OTOH, this compiles perfectly and prints false
as expected:
public class Test {
public static void main(String args) {
Object t = new Test();
// compiles fine since Object is a parent class to String
System.out.println(t instanceof String);
}
}
As mentioned in other answers, the canonical typical usage of instanceof
is for checking if an identifier is referring to a more specific type. Example:
Object someobject = ... some code which gets something that might be a button ...
if (someobject instanceof Button) {
// then if someobject is in fact a button this block gets executed
} else {
// otherwise execute this block
}
Note however, that the type of the left-hand expression must be a parent type of the right hand expression (see JLS 15.20.2 and Java Puzzlers, #50, pp114). For example, the following will fail to compile:
public class Test {
public static void main(String args) {
System.out.println(new Test() instanceof String); // will fail to compile
}
}
This fails to compile with the message:
Test.java:6: error: inconvertible types
System.out.println(t instanceof String);
^
required: String
found: Test
1 error
As Test
is not a parent class of String
. OTOH, this compiles perfectly and prints false
as expected:
public class Test {
public static void main(String args) {
Object t = new Test();
// compiles fine since Object is a parent class to String
System.out.println(t instanceof String);
}
}
answered Dec 13 '13 at 21:29
Adam Parkin
7,34294569
7,34294569
Thanks for linking to the spec!
– jpaugh
Jan 28 '16 at 19:26
add a comment |
Thanks for linking to the spec!
– jpaugh
Jan 28 '16 at 19:26
Thanks for linking to the spec!
– jpaugh
Jan 28 '16 at 19:26
Thanks for linking to the spec!
– jpaugh
Jan 28 '16 at 19:26
add a comment |
up vote
1
down vote
public class Animal{ float age; }
public class Lion extends Animal { int claws;}
public class Jungle {
public static void main(String args) {
Animal animal = new Animal();
Animal animal2 = new Lion();
Lion lion = new Lion();
Animal animal3 = new Animal();
Lion lion2 = new Animal(); //won't compile (can't reference super class object with sub class reference variable)
if(animal instanceof Lion) //false
if(animal2 instanceof Lion) //true
if(lion insanceof Lion) //true
if(animal3 instanceof Animal) //true
}
}
add a comment |
up vote
1
down vote
public class Animal{ float age; }
public class Lion extends Animal { int claws;}
public class Jungle {
public static void main(String args) {
Animal animal = new Animal();
Animal animal2 = new Lion();
Lion lion = new Lion();
Animal animal3 = new Animal();
Lion lion2 = new Animal(); //won't compile (can't reference super class object with sub class reference variable)
if(animal instanceof Lion) //false
if(animal2 instanceof Lion) //true
if(lion insanceof Lion) //true
if(animal3 instanceof Animal) //true
}
}
add a comment |
up vote
1
down vote
up vote
1
down vote
public class Animal{ float age; }
public class Lion extends Animal { int claws;}
public class Jungle {
public static void main(String args) {
Animal animal = new Animal();
Animal animal2 = new Lion();
Lion lion = new Lion();
Animal animal3 = new Animal();
Lion lion2 = new Animal(); //won't compile (can't reference super class object with sub class reference variable)
if(animal instanceof Lion) //false
if(animal2 instanceof Lion) //true
if(lion insanceof Lion) //true
if(animal3 instanceof Animal) //true
}
}
public class Animal{ float age; }
public class Lion extends Animal { int claws;}
public class Jungle {
public static void main(String args) {
Animal animal = new Animal();
Animal animal2 = new Lion();
Lion lion = new Lion();
Animal animal3 = new Animal();
Lion lion2 = new Animal(); //won't compile (can't reference super class object with sub class reference variable)
if(animal instanceof Lion) //false
if(animal2 instanceof Lion) //true
if(lion insanceof Lion) //true
if(animal3 instanceof Animal) //true
}
}
edited Sep 7 '15 at 14:37
Walery Strauch
3,72763448
3,72763448
answered Dec 13 '14 at 18:42
bangbang
4861416
4861416
add a comment |
add a comment |
up vote
1
down vote
Can be used as a shorthand in equality check.
So this code
if(ob != null && this.getClass() == ob.getClass) {
}
Can be written as
if(ob instanceOf ClassA) {
}
add a comment |
up vote
1
down vote
Can be used as a shorthand in equality check.
So this code
if(ob != null && this.getClass() == ob.getClass) {
}
Can be written as
if(ob instanceOf ClassA) {
}
add a comment |
up vote
1
down vote
up vote
1
down vote
Can be used as a shorthand in equality check.
So this code
if(ob != null && this.getClass() == ob.getClass) {
}
Can be written as
if(ob instanceOf ClassA) {
}
Can be used as a shorthand in equality check.
So this code
if(ob != null && this.getClass() == ob.getClass) {
}
Can be written as
if(ob instanceOf ClassA) {
}
answered Sep 6 '16 at 7:23
mirmdasif
3,27811523
3,27811523
add a comment |
add a comment |
up vote
0
down vote
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
add a comment |
up vote
0
down vote
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
add a comment |
up vote
0
down vote
up vote
0
down vote
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
answered Sep 5 '11 at 23:44
Benjamin Udink ten Cate
10.2k33359
10.2k33359
add a comment |
add a comment |
up vote
0
down vote
Instance of keyword is helpful when you want to know particular object's instance .
Suppose you are throw exception and when you have catch then perform sum custom operation and then again continue as per your logic (throws or log etc)
Example :
1) User created custom exception "InvalidExtensionsException" and throw it as per logic
2) Now in catch block
catch (Exception e) {
perform sum logic if exception type is "InvalidExtensionsException"
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
3) If you are not checking instance of and exception type is Null pointer exception your code will break.
So your logic should be inside of instance of
if (e instanceof InvalidExtensionsException){
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
}
Above example is wrong coding practice However this example is help you to understand use of instance of it.
add a comment |
up vote
0
down vote
Instance of keyword is helpful when you want to know particular object's instance .
Suppose you are throw exception and when you have catch then perform sum custom operation and then again continue as per your logic (throws or log etc)
Example :
1) User created custom exception "InvalidExtensionsException" and throw it as per logic
2) Now in catch block
catch (Exception e) {
perform sum logic if exception type is "InvalidExtensionsException"
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
3) If you are not checking instance of and exception type is Null pointer exception your code will break.
So your logic should be inside of instance of
if (e instanceof InvalidExtensionsException){
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
}
Above example is wrong coding practice However this example is help you to understand use of instance of it.
add a comment |
up vote
0
down vote
up vote
0
down vote
Instance of keyword is helpful when you want to know particular object's instance .
Suppose you are throw exception and when you have catch then perform sum custom operation and then again continue as per your logic (throws or log etc)
Example :
1) User created custom exception "InvalidExtensionsException" and throw it as per logic
2) Now in catch block
catch (Exception e) {
perform sum logic if exception type is "InvalidExtensionsException"
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
3) If you are not checking instance of and exception type is Null pointer exception your code will break.
So your logic should be inside of instance of
if (e instanceof InvalidExtensionsException){
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
}
Above example is wrong coding practice However this example is help you to understand use of instance of it.
Instance of keyword is helpful when you want to know particular object's instance .
Suppose you are throw exception and when you have catch then perform sum custom operation and then again continue as per your logic (throws or log etc)
Example :
1) User created custom exception "InvalidExtensionsException" and throw it as per logic
2) Now in catch block
catch (Exception e) {
perform sum logic if exception type is "InvalidExtensionsException"
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
3) If you are not checking instance of and exception type is Null pointer exception your code will break.
So your logic should be inside of instance of
if (e instanceof InvalidExtensionsException){
InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
}
Above example is wrong coding practice However this example is help you to understand use of instance of it.
answered Jul 27 '16 at 15:34
vaquar khan
2,83311534
2,83311534
add a comment |
add a comment |
up vote
0
down vote
Most people have correctly explained the "What" of this question but no one explained "How" correctly.
So here's a simple illustration:
String s = new String("Hello");
if (s instanceof String) System.out.println("s is instance of String"); // True
if (s instanceof Object) System.out.println("s is instance of Object"); // True
//if (s instanceof StringBuffer) System.out.println("s is instance of StringBuffer"); // Compile error
Object o = (Object)s;
if (o instanceof StringBuffer) System.out.println("o is instance of StringBuffer"); //No error, returns False
else System.out.println("Not an instance of StringBuffer"); //
if (o instanceof String) System.out.println("o is instance of String"); //True
Outputs:
s is instance of String
s is instance of Object
Not an instance of StringBuffer
o is instance of String
The reason for compiler error when comparing s
with StringBuffer is well explained in docs:
You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
which implies the LHS must either be an instance of RHS or of a Class that either implements RHS or extends RHS.
How to use use instanceof then?
Since every Class extends Object, type-casting LHS to object will always work in your favour:
String s = new String("Hello");
if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //No compiler error now :)
else System.out.println("Not an instance of StringBuffer");
Outputs:
Not an instance of StringBuffer
In the last example, why is it returning "Not an instance of StringBuffer"? Since you typecasted s to Object on LHS and checking if it is an instanceof RHS,if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //shouldn't this be true
, since we are typecasting s to Object?
– sofs1
Sep 12 at 5:17
Because s is a reference to String object (Java employs dynamic polymorphism unlike C++) and String isn't a subclass of StringBuffer.
– sziraqui
Sep 13 at 10:18
add a comment |
up vote
0
down vote
Most people have correctly explained the "What" of this question but no one explained "How" correctly.
So here's a simple illustration:
String s = new String("Hello");
if (s instanceof String) System.out.println("s is instance of String"); // True
if (s instanceof Object) System.out.println("s is instance of Object"); // True
//if (s instanceof StringBuffer) System.out.println("s is instance of StringBuffer"); // Compile error
Object o = (Object)s;
if (o instanceof StringBuffer) System.out.println("o is instance of StringBuffer"); //No error, returns False
else System.out.println("Not an instance of StringBuffer"); //
if (o instanceof String) System.out.println("o is instance of String"); //True
Outputs:
s is instance of String
s is instance of Object
Not an instance of StringBuffer
o is instance of String
The reason for compiler error when comparing s
with StringBuffer is well explained in docs:
You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
which implies the LHS must either be an instance of RHS or of a Class that either implements RHS or extends RHS.
How to use use instanceof then?
Since every Class extends Object, type-casting LHS to object will always work in your favour:
String s = new String("Hello");
if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //No compiler error now :)
else System.out.println("Not an instance of StringBuffer");
Outputs:
Not an instance of StringBuffer
In the last example, why is it returning "Not an instance of StringBuffer"? Since you typecasted s to Object on LHS and checking if it is an instanceof RHS,if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //shouldn't this be true
, since we are typecasting s to Object?
– sofs1
Sep 12 at 5:17
Because s is a reference to String object (Java employs dynamic polymorphism unlike C++) and String isn't a subclass of StringBuffer.
– sziraqui
Sep 13 at 10:18
add a comment |
up vote
0
down vote
up vote
0
down vote
Most people have correctly explained the "What" of this question but no one explained "How" correctly.
So here's a simple illustration:
String s = new String("Hello");
if (s instanceof String) System.out.println("s is instance of String"); // True
if (s instanceof Object) System.out.println("s is instance of Object"); // True
//if (s instanceof StringBuffer) System.out.println("s is instance of StringBuffer"); // Compile error
Object o = (Object)s;
if (o instanceof StringBuffer) System.out.println("o is instance of StringBuffer"); //No error, returns False
else System.out.println("Not an instance of StringBuffer"); //
if (o instanceof String) System.out.println("o is instance of String"); //True
Outputs:
s is instance of String
s is instance of Object
Not an instance of StringBuffer
o is instance of String
The reason for compiler error when comparing s
with StringBuffer is well explained in docs:
You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
which implies the LHS must either be an instance of RHS or of a Class that either implements RHS or extends RHS.
How to use use instanceof then?
Since every Class extends Object, type-casting LHS to object will always work in your favour:
String s = new String("Hello");
if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //No compiler error now :)
else System.out.println("Not an instance of StringBuffer");
Outputs:
Not an instance of StringBuffer
Most people have correctly explained the "What" of this question but no one explained "How" correctly.
So here's a simple illustration:
String s = new String("Hello");
if (s instanceof String) System.out.println("s is instance of String"); // True
if (s instanceof Object) System.out.println("s is instance of Object"); // True
//if (s instanceof StringBuffer) System.out.println("s is instance of StringBuffer"); // Compile error
Object o = (Object)s;
if (o instanceof StringBuffer) System.out.println("o is instance of StringBuffer"); //No error, returns False
else System.out.println("Not an instance of StringBuffer"); //
if (o instanceof String) System.out.println("o is instance of String"); //True
Outputs:
s is instance of String
s is instance of Object
Not an instance of StringBuffer
o is instance of String
The reason for compiler error when comparing s
with StringBuffer is well explained in docs:
You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
which implies the LHS must either be an instance of RHS or of a Class that either implements RHS or extends RHS.
How to use use instanceof then?
Since every Class extends Object, type-casting LHS to object will always work in your favour:
String s = new String("Hello");
if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //No compiler error now :)
else System.out.println("Not an instance of StringBuffer");
Outputs:
Not an instance of StringBuffer
answered Jul 22 at 13:53
sziraqui
1,22211125
1,22211125
In the last example, why is it returning "Not an instance of StringBuffer"? Since you typecasted s to Object on LHS and checking if it is an instanceof RHS,if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //shouldn't this be true
, since we are typecasting s to Object?
– sofs1
Sep 12 at 5:17
Because s is a reference to String object (Java employs dynamic polymorphism unlike C++) and String isn't a subclass of StringBuffer.
– sziraqui
Sep 13 at 10:18
add a comment |
In the last example, why is it returning "Not an instance of StringBuffer"? Since you typecasted s to Object on LHS and checking if it is an instanceof RHS,if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //shouldn't this be true
, since we are typecasting s to Object?
– sofs1
Sep 12 at 5:17
Because s is a reference to String object (Java employs dynamic polymorphism unlike C++) and String isn't a subclass of StringBuffer.
– sziraqui
Sep 13 at 10:18
In the last example, why is it returning "Not an instance of StringBuffer"? Since you typecasted s to Object on LHS and checking if it is an instanceof RHS,
if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //shouldn't this be true
, since we are typecasting s to Object?– sofs1
Sep 12 at 5:17
In the last example, why is it returning "Not an instance of StringBuffer"? Since you typecasted s to Object on LHS and checking if it is an instanceof RHS,
if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //shouldn't this be true
, since we are typecasting s to Object?– sofs1
Sep 12 at 5:17
Because s is a reference to String object (Java employs dynamic polymorphism unlike C++) and String isn't a subclass of StringBuffer.
– sziraqui
Sep 13 at 10:18
Because s is a reference to String object (Java employs dynamic polymorphism unlike C++) and String isn't a subclass of StringBuffer.
– sziraqui
Sep 13 at 10:18
add a comment |
up vote
-1
down vote
You could use Map to make higher abstraction on instance of
private final Map<Class, Consumer<String>> actions = new HashMap<>();
Then having such map add some action to it:
actions.put(String.class, new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("action for String");
}
};
Then having an Object of not known type you could get specific action from that map:
actions.get(someObject).accept(someObject)
add a comment |
up vote
-1
down vote
You could use Map to make higher abstraction on instance of
private final Map<Class, Consumer<String>> actions = new HashMap<>();
Then having such map add some action to it:
actions.put(String.class, new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("action for String");
}
};
Then having an Object of not known type you could get specific action from that map:
actions.get(someObject).accept(someObject)
add a comment |
up vote
-1
down vote
up vote
-1
down vote
You could use Map to make higher abstraction on instance of
private final Map<Class, Consumer<String>> actions = new HashMap<>();
Then having such map add some action to it:
actions.put(String.class, new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("action for String");
}
};
Then having an Object of not known type you could get specific action from that map:
actions.get(someObject).accept(someObject)
You could use Map to make higher abstraction on instance of
private final Map<Class, Consumer<String>> actions = new HashMap<>();
Then having such map add some action to it:
actions.put(String.class, new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("action for String");
}
};
Then having an Object of not known type you could get specific action from that map:
actions.get(someObject).accept(someObject)
answered May 6 '16 at 14:03
tomekl007
192
192
add a comment |
add a comment |
up vote
-1
down vote
class Test48{
public static void main (String args){
Object Obj=new Hello();
//Hello obj=new Hello;
System.out.println(Obj instanceof String);
System.out.println(Obj instanceof Hello);
System.out.println(Obj instanceof Object);
Hello h=null;
System.out.println(h instanceof Hello);
System.out.println(h instanceof Object);
}
}
Don't post code only answers on StackOverflow. Please go ahead and add an explaination.
– L. Guthardt
Jul 9 at 6:44
add a comment |
up vote
-1
down vote
class Test48{
public static void main (String args){
Object Obj=new Hello();
//Hello obj=new Hello;
System.out.println(Obj instanceof String);
System.out.println(Obj instanceof Hello);
System.out.println(Obj instanceof Object);
Hello h=null;
System.out.println(h instanceof Hello);
System.out.println(h instanceof Object);
}
}
Don't post code only answers on StackOverflow. Please go ahead and add an explaination.
– L. Guthardt
Jul 9 at 6:44
add a comment |
up vote
-1
down vote
up vote
-1
down vote
class Test48{
public static void main (String args){
Object Obj=new Hello();
//Hello obj=new Hello;
System.out.println(Obj instanceof String);
System.out.println(Obj instanceof Hello);
System.out.println(Obj instanceof Object);
Hello h=null;
System.out.println(h instanceof Hello);
System.out.println(h instanceof Object);
}
}
class Test48{
public static void main (String args){
Object Obj=new Hello();
//Hello obj=new Hello;
System.out.println(Obj instanceof String);
System.out.println(Obj instanceof Hello);
System.out.println(Obj instanceof Object);
Hello h=null;
System.out.println(h instanceof Hello);
System.out.println(h instanceof Object);
}
}
answered Jul 9 at 6:15
sajid sadiq
1
1
Don't post code only answers on StackOverflow. Please go ahead and add an explaination.
– L. Guthardt
Jul 9 at 6:44
add a comment |
Don't post code only answers on StackOverflow. Please go ahead and add an explaination.
– L. Guthardt
Jul 9 at 6:44
Don't post code only answers on StackOverflow. Please go ahead and add an explaination.
– L. Guthardt
Jul 9 at 6:44
Don't post code only answers on StackOverflow. Please go ahead and add an explaination.
– L. Guthardt
Jul 9 at 6:44
add a comment |
up vote
-2
down vote
Very simple code example:
If (object1 instanceof Class1) {
// do something
} else if (object1 instanceof Class2) {
// do something different
}
Be careful here. In the example above, if Class1 is Object, the first comparison will always be true. So, just like with exceptions, hierarchical order matters!
add a comment |
up vote
-2
down vote
Very simple code example:
If (object1 instanceof Class1) {
// do something
} else if (object1 instanceof Class2) {
// do something different
}
Be careful here. In the example above, if Class1 is Object, the first comparison will always be true. So, just like with exceptions, hierarchical order matters!
add a comment |
up vote
-2
down vote
up vote
-2
down vote
Very simple code example:
If (object1 instanceof Class1) {
// do something
} else if (object1 instanceof Class2) {
// do something different
}
Be careful here. In the example above, if Class1 is Object, the first comparison will always be true. So, just like with exceptions, hierarchical order matters!
Very simple code example:
If (object1 instanceof Class1) {
// do something
} else if (object1 instanceof Class2) {
// do something different
}
Be careful here. In the example above, if Class1 is Object, the first comparison will always be true. So, just like with exceptions, hierarchical order matters!
answered Sep 5 '11 at 23:38
mjuarez
9,55973651
9,55973651
add a comment |
add a comment |
up vote
-2
down vote
The instanceof operator is used to check whether the object is an instance of the specified type. (class or subclass or interface).
The instanceof is also known as type comparison operator because it compares the instance with type. It returns either true or false.
class Simple1 {
public static void main(String args) {
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1); //true
}
}
If we apply the instanceof operator with any variable that has null value, it returns false.
add a comment |
up vote
-2
down vote
The instanceof operator is used to check whether the object is an instance of the specified type. (class or subclass or interface).
The instanceof is also known as type comparison operator because it compares the instance with type. It returns either true or false.
class Simple1 {
public static void main(String args) {
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1); //true
}
}
If we apply the instanceof operator with any variable that has null value, it returns false.
add a comment |
up vote
-2
down vote
up vote
-2
down vote
The instanceof operator is used to check whether the object is an instance of the specified type. (class or subclass or interface).
The instanceof is also known as type comparison operator because it compares the instance with type. It returns either true or false.
class Simple1 {
public static void main(String args) {
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1); //true
}
}
If we apply the instanceof operator with any variable that has null value, it returns false.
The instanceof operator is used to check whether the object is an instance of the specified type. (class or subclass or interface).
The instanceof is also known as type comparison operator because it compares the instance with type. It returns either true or false.
class Simple1 {
public static void main(String args) {
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1); //true
}
}
If we apply the instanceof operator with any variable that has null value, it returns false.
answered Feb 10 '17 at 14:40
Viraj Pai
211
211
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7313559%2fwhat-is-the-instanceof-operator-used-for-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
31
There is nothing wrong with asking questions here, but if you are learning Java you might want to get a book. Any decent Java book would have the answer to this question and the next 1000 you're going to have.
– James K Polk
Sep 5 '11 at 23:32
Such an operator has many specific uses. This would be a specific question if it asked for an explanation of one of the examples that did not make sense to you.
– Raedwald
Aug 23 '13 at 7:15
1
The answers below are correct, however note that instanceof is an overused operator 9 times out of 10 it can be replaced by a proper use of polymorphism (not always, but often)
– Richard Tingle
Aug 24 '13 at 18:22
I'd go one further than Richard: I have NEVER seen a valid use of instanceof. It's only useful for quick hacks on top of poorly designed code. If you don't like OOP, write in another language (there are plenty). Just say, "no" to instanceof!
– Scott Biggs
Nov 27 '15 at 22:14
4
@ScottBiggs Is there a good alternative to
instanceof
when overridingequals
?– Ben Aaronson
Sep 7 '16 at 14:55