• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof operator

 
Phillipe Rodrigues
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?



Gavin
 
Campbell Ritchie
Sheriff
Pie
Posts: 50289
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic