This week's giveaway is in the Beginning Java forum.
We're giving away four copies of Bad Programming Practices 101 (e-book) and have Karl Beecher on-line!
See this thread for details.
Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

instanceof operator  RSS feed

 
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
15.20.2 Type Comparison Operator instanceof

No matter "s" is initialized or not.A compile-time error will occurs.
 
Those cherries would go best on cherry cheesecake. Don't put those cherries on this tiny ad:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!