Why is this line of code in Java not printing the message?
System.out.println("a instanceof String:"+a instanceof String);
Why is it just printing true and not the String before it???
Ah, the joys of operator precedence. That line is effectively:
System.out.println(("a instanceof String:" + a) instanceof String);
... so you're doing string concatenation, and then checking whether the result is a string. So it will always print true
, regardless of the value of a
.
You just need parentheses
System.out.println("a instanceof String:" + (a instanceof String));
See the Java tutorial page on operators for a precedence list.
See more on this question at Stackoverflow