File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes instanceof operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instanceof operator" Watch "instanceof operator" New topic

instanceof operator

Phillipe Rodrigues
Ranch Hand

Joined: Oct 30, 2007
Posts: 165
public String getNot(String value){
if(val instanceof Integer)
Integer temp =(Integer)val;
String new_val =String.valueOf(temp.intValue());
return new_val;


What role does instanceof operator play in the above code?

In a tutorial for instanceof te below was given:
if (objectA instanceof objectB)will yield true if objectA can be upcast to objectB.

ObjectA can be upcast to objectB.means what with reference to above code.

Gavin Tranter
Ranch Hand

Joined: Jan 01, 2007
Posts: 333
Have you tried looking at the java documentation for instanceof?
Maybe a google search? The top entry on my google search just came back with an interesting discussion on the sun java forums.

Basicly, it does what it says. It returns true is objectB is an instance of objectA.

Upcasting simply means you are casting the object "up" the inheritance tree. If you are having trouble with this, I really do suggest you go to the Java site and read up on Object casting, it is a fundemental concept.

Give C extends A, and B extends Object, what do you think the result of these would be?

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46389
It won't compile because you haven't declared a variable "val."

If you had used "value" instead, value is a String which cannot be upcast or downcast to Integer, so it prevents a ClassCastException.

It also prevents the body of the "if" block executing, which means the new_val variable is never initialised, which means it is never returned, which means that not every path through the method returns a value, which means it won't compile.
And even if you did get to return a value, it would be out of scope after the "if" block so it still won't compile.
I agree. Here's the link:
subject: instanceof operator
It's not a secret anymore!