• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

instanceof operator

 
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic