9

これはどのように作動しますか?答えが見つからないようです。

boolean bool=true;
System.out.println("the value of bool is : " + true);
//or
System.out.println("the value of bool is : " + bool);
  • 舞台裏で起こっていることは何ですか?
  • ブール値は暗黙的に型キャストできないため、ブール値はどのように文字列にキャストされますか?
  • Autoboxing / Unboxingは関係していますか?
  • 方法は似ているtoString()String.valueOf()、何らかの形で関与していますか?
4

3 に答える 3

19

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 intermediate String 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        
于 2012-12-15T18:28:23.180 に答える
2

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.

于 2012-12-15T18:26:14.617 に答える
2

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.

于 2012-12-15T18:28:30.890 に答える