how does this work? I can't seem to find an answer.
boolean bool=true;
System.out.println("the value of bool is : " + true);
//or
System.out.println("the value of bool is : " + bool);
- What are the things that are going on behind the scene?
- how does the boolean gets casted to the String as a boolean cannot be implicitly type casted?
- Is Autoboxing/Unboxing involved?
- Are methods like
toString()
orString.valueOf()
are involved in some way?
The exact rules are spelled out in the Java Language Specification, §5.1.11. String Conversion
According to those rules,
"str" + bool
is equivalent to:That said, the compiler is permitted considerable leeway in how exactly the overall expression is evaluated. From JLS §15.18.1. String Concatenation Operator +:
For example, with my compiler the following:
is exactly equivalent to:
They result in identical bytecodes:
It's a compiler thing. If the right operand for concatenation is an object, the object is sent the
toString()
method whereas if the operand is a primitive then the compiler knows which type-specific behavior to use to convert the primitive to an String.The compiler translates it to
The rules of concatenation and conversion are explained in the JLS.