This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instanceof operator" Watch "instanceof operator" New topic
Author

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.


Thanks,
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?



Gavin
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37923
    
  22
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.
 
wood burning stoves
 
subject: instanceof operator
 
Similar Threads
instanceof operator
Finding an object reference
JPQL - Query Parameter
Garbage collector vs circular reference
use an instance that is created