aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes instanceof operator Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "instanceof operator" Watch "instanceof operator" New topic
Author

instanceof operator

Swapnil Trivedi
Ranch Hand

Joined: Jun 06, 2006
Posts: 106
In the following code:

Public class AA{
static String s;
public static void main(String args[]){
AA a = new AA();
if (s instanceof AA){
System.out.println("true String"); }

Here the author says that s is not an instance of String because it's not initialized. Why so?? Can anybody explain it to me...


Thanks
Swapnil


SCJP 5.0<br />-----------<br />"Help Ever && Hurt Never"
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
Hi...

I don't know wat author is trying to explain.

Wat my logic says dat instanceof operator is always checked at compilation time and wat compiler will check is the reference tpe of s. If its of type AA or super class of AA (e.g. java.lang.Object), then compiler is HAPPY.

otherwise compiler will give error--->>> inconvertible types.

As per above, ur code will give compilation error inconvertible types in if condition.

regards

Naseem Khan


Asking Smart Questions FAQ - How To Put Your Code In Code Tags
joshua antony
Ranch Hand

Joined: Jun 05, 2006
Posts: 117
The author is correct.
s instanceof AA in your code means it is checked whether the object refered
by s is an instance of AA class.
And since you have not initialised s it will be set to null.
so s instanceof String will check whether null is instance of string, which is obviously not.

Regards,
joshua
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
15.20.2 Type Comparison Operator instanceof

No matter "s" is initialized or not.A compile-time error will occurs.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: instanceof operator
 
Similar Threads
instanceof prblem help me
instanceof key word
instanceof operator
Polymorphism example - where would we ever use this construct?
Inheritance-1