Language Support for String Concatenation

There is another String feature with special built-in compiler support: concatenation, or joining of two Strings. Whenever a String is one operand of the “+” operator, the system does not do addition. Instead, the other operand (whatever it is, object or primitive) will be converted to a String, and the result is the two Strings appended together. If the operand is an object, it is converted to a String by calling its toString() method. The toString() method of Object is described on page 58; String has its own special version of this.

Concatenation is a piece of “magic” extra operator support for type String. The “+” operator used to be the only operator that could be applied to an object, until unboxing was brought into JDK 1.5. You will use this String “+” feature in many places. Here are a few examples:

  • To print out a variable and some text saying what it is:

    System.out.println( "x has value " + x
                             + " and y has value " + y );

  • To break a long String literal down into smaller strings and continue it across several lines:

     "Thomas the Tank Engine and the naughty "
    + "Engine-driver who tied down Thomas's Boiler Safety Valve"
    + "and How They Found Pieces of Thomas in Three Counties."

  • To convert the value to a String (concatenating an empty String with a value of a primitive type is a Java idiom):

    int i = 256;
         ...
    ... "" + i // yields a String containing the value of i.

That's much shorter than the alternative of using the conversion method of the String class String.valueOf( i ).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.156.235