• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

instanceof Question

 
Greenhorn
Posts: 1
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This line:


means this:


it does not mean this:
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic