instanceOf operator in java

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???

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow