4

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

3
  • 1
    Maybe you should tell us what a is? Commented Apr 1, 2017 at 11:42
  • 1
    @RC.: As it happens, it doesn't matter. But yes, a minimal reproducible example would be better. Commented Apr 1, 2017 at 11:43
  • @JonSkeet I saw your answer, so yes it doesn't matter in that case ;) Commented Apr 1, 2017 at 11:44

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Your code will be executed as follows:

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

So, the whole string i.e., ("a instanceof String:"+a) has been considered for the instanceof check.

In order to print, "a instanceof String:true", you need to use parenthesis at the right place:

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

Comments

1

You have to use brackets.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.