InstanceOf statement in java

Why doesn't this line of code in Java print a message?

System.out.println("a instanceof String:"+a instanceof String);

Why does it just print true and not String before it ???

+4
source share
3 answers

Ah, the joy of operator priority. This line is effective:

System.out.println(("a instanceof String:" + a) instanceof String);

... so you do string concatenation and then check if the result is a string. Therefore, it will always print true, regardless of value a.

You need brackets

System.out.println("a instanceof String:" + (a instanceof String));

Refer to the Java tutorial page for operators for a list of priorities.

+8
source

Your code will be executed as follows:

System.out.println(("a instanceof String:"+a) instanceof String);

So, the whole chain, i.e. ("a instanceof String:"+a)has been reviewed for verification instanceof.

, "a instanceof String:true", :

System.out.println("a instanceof String:" + (a instanceof String));
+3

You must use parentheses.

System.out.println(("a instanceof String:"+a) instanceof String);
+1
source

Source: https://habr.com/ru/post/1673768/


All Articles