Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof doubt?

 
Joe Harry
Ranch Hand
Posts: 10106
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys, I tried the code below and not able to understand the semantics of the instanceof operator??

class Sample{
static String s;
public static void main(String args[]){
if(s instanceof String){
System.out.println("true");
else
System.out.println("false");
}
}

Why the o/p is false?? Under which circumstances will the instanceof operator produce a compile time error??
 
anvesh charuvaka
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable s is not a reference to any object and since it is initialized to null ( all class and instance variables are initialized with default values) it gives false with instanceof operator.

If you assign some object to it and then try it the instanceof will give true.
 
wang gang
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have tested the code,because the "}" is not needed. Or they can't compile.
If you delete the last "}", the result is false. Just the static variable "s" isn't initialized. So s==null; null (instanceof String)==false.
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jothi,
I think you have got the answer for the output the program produces.
Under which circumstances will the instanceof operator produce a compile time error??

It will produce an error if one will try to compare an instance of and object with an another one which is not in the same inheritance hierarchy except comparision of null(will always return false) .For e.g.


Both String and StringBuffer are sibling parent being the CharSequence,hence are not a part of same inheritance tree.
[ December 11, 2006: Message edited by: Sanjeev Kumar Singh ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic