Alex Rivera | Logout

primitive-boolean To String concatenation/conversion

Asked 2012-12-15T18:22:39.133
9

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() or String.valueOf() are involved in some way?
Edit
Report

1 Answer

20

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
answered 2012-12-15T18:28:23.180

Your Answer