Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 850
Ankit Avatar asked Dec 14 '22 23:12

Ankit


1 Answers

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.

like image 123
Jon Skeet Avatar answered Dec 29 '22 21:12

Jon Skeet