• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

System.out.println("t is an Object is: " + t instanceof Object);

 
Christian Orphall
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have found a strange issue:
System.out.println("t is an Object is: " + t instanceof Object);
System.out.println("t is an Object is: " + (t instanceof Object));
is not the same!
The first line produces "true", the second line "t is an Object is: true"
A little amazing, any idea ?
Chris
class test {
private int x; // some stuff
public static void main (String[] args) {

test t = new test();

System.out.println("t is an Object is: " + t instanceof Object);
System.out.println("t is an Object is: " + (t instanceof Object));
}

}
produces the output:

true
t is an Object is: true
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Christian, welcome to JavaRanch!
In the first instance: "t is an Object is: " + t instanceof Object, the grouping is: ("t is an Object is: " + t) instanceof Object. The object referred to by t is coerced to its String value and that value is joined onto the end of "t is an Object is: ", resulting in another String. That String is, of course, an instance of Object. So you get the result true printed.
In the second case you are evaluating in a different order: the object referred to by t is an instance of Object, so you get a boolean true. The boolean value true is coerced to the string "true" and that is appended onto "t is an Object is: ", resulting in "t is an Object is: true". That last String is what gets printed.
So no suprises here, really
 
Christian Orphall
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!
Chris
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic