2

Is there any difference between

System.out.println(true);

and

System.out.println("true");

Although the output I see is the same, is there any difference with respect to usage or coding style?

Eran
  • 387,369
  • 54
  • 702
  • 768
Leo
  • 5,017
  • 6
  • 32
  • 55
  • Speaking about coding-style, I would do #2. But since you are printing a boolean value (that comes from a boolean variable I suppose), I would call `System.out.println(myBoolVariable);`. It's not clear what would be the real use case of your suggestion. You shouldn't bother about this and let the appropriate overloaded method be called. – Alexis C. Jan 02 '15 at 13:49

4 Answers4

6

In the first option you pass a boolean to the PrintWriter's println method while in the second you are passing a String, so different println methods are called. In the end, the boolean in the first case is converted to a String, so the end result is the same.

If you only print a single boolean literal, println(true) is shorter. If you combine that literal with other Strings, println("value = true") would make more sense than println("value="+true).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • In case of `println("value="+true)`what argument are we passing to the println method? – Leo Jan 02 '15 at 13:52
  • 2
    @Leo You would be passing a `String`, since `true` would be converted to `String` and concatenated to `"value="` before being passed to `println`. – Eran Jan 02 '15 at 13:54
4

true gives boolean value and "true" means charsequence or string value

Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
2

The PrintWriter's println() method is overriden for many objects and primitives.

If you look internally it uses

write(String.valueOf(obj));

so the obj.toString() is what does all the magic :)

yUdoDis
  • 1,098
  • 6
  • 15
0

Both are different true is boolean literal And "true" is String literal