File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes instanceof doubt? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "instanceof doubt?" Watch "instanceof doubt?" New topic
Author

instanceof doubt?

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9618
    
    2

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


SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
anvesh charuvaka
Greenhorn

Joined: Sep 25, 2006
Posts: 11
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

Joined: Dec 08, 2006
Posts: 2
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.


faquir
Sanjeev Singh
Ranch Hand

Joined: Nov 01, 2006
Posts: 381
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 ]

~Sanjeev Singh<br />SCJP 1.5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instanceof doubt?