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
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 exact rules are spelled out in the Java Language Specification, §5.1.11. String Conversion
According to those rules, "str" + bool
is equivalent to:
"str" + new Boolean(bool).toString()
That said, the compiler is permitted considerable leeway in how exactly the overall expression is evaluated. From JLS §15.18.1. String Concatenation Operator +:
An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the
StringBuffer
class or a similar technique to reduce the number of intermediateString
objects that are created by evaluation of an expression.For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.
For example, with my compiler the following:
boolean bool = true;
System.out.println("the value of bool is : " + bool);
is exactly equivalent to:
boolean bool = true;
System.out.println(new StringBuilder("the value of bool is : ").append(bool).toString());
They result in identical bytecodes:
Code:
0: iconst_1
1: istore_1
2: getstatic #59 // Field java/lang/System.out:Ljava/io/PrintStream;
5: new #166 // class java/lang/StringBuilder
8: dup
9: ldc #168 // String the value of bool is :
11: invokespecial #170 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
14: iload_1
15: invokevirtual #172 // Method java/lang/StringBuilder.append:(Z)Ljava/lang/StringBuilder;
18: invokevirtual #176 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
21: invokevirtual #69 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
24: return
The compiler translates it to
StringBuilder sb = new StringBuilder("the value of bool is : ");
sb.append(true);
System.out.println(sb.toString());
The rules of concatenation and conversion are explained in the JLS.