• Post Reply Bookmark Topic Watch Topic
  • New Topic

instanceof Question  RSS feed

 
Jesús Calvo
Greenhorn
Posts: 1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
  I have a problem with this different codes:
1)
Hippo nullHippo = null;
boolean b5 = nullHippo instanceof Object;
System.out.println("hipo " + b5);

2) Hippo nullHippo = null;
System.out.println("hipo " + nullHippo instanceof Object);

The first one prints "hipo false", as expected, but... does somebody know why the second one prints "hipo true"?

Thanks.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Because hipo null is an instance of Object. What you are doing is concatenating the String "hipo" to the Hippo reference with the + operator and then seeing whether the whole thing is an instance of Object.
Remember the rules are: always go left‑to‑right. Higher precedence operators on the right, or right‑associative operators, are then taken into consideration.
Remember also that + has a higher precedence than instanceof, so you are still going left‑to‑right.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This line:


means this:


it does not mean this:
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesús Calvo wrote:The first one prints "hipo false", as expected, but... does somebody know why the second one prints "hipo true"?

Hopefully, Campbell and Jesper have answered for you.
Nice question though, +1 - took me a few seconds to work out.

Hopefully, this also illustrates that 'instanceof' is an operator - just like '+' and '*' - even though it doesn't look like one.
And as such, it has a precedence.

HIH

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!