Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The compiler uses theStringBuilder
class behind the scenes to handle literal strings and concatenation. As you know, you specify literal strings between double quotes:You can use literal strings anywhere you would use a"Hello World!"String
object. For example,System.out.println
accepts a string argument, so you could use a literal string there:You can also useSystem.out.println("Might I add that you look lovely today.");String
methods directly from a literal string:Because the compiler automatically creates a new string object for every literal string it encounters, you can use a literal string to initialize a string:int len = "Goodbye Cruel World".length();The preceding construct is equivalent to, but more efficient than, this one, which ends up creating two identical strings:String s = "Hola Mundo";You can use + to concatenate strings:String s = new String("Hola Mundo"); //don't do thisBehind the scenes, the compiler uses string buffers to implement concatenation. The preceding example compiles to something equivalent to:String cat = "cat"; System.out.println("con" + cat + "enation");You can also use the + operator to append to a string values that are not themselves strings:String cat = "cat"; System.out.println(new StringBuffer().append("con"). append(cat).append("enation").toString());The compiler implicitly converts the nonstring value (the integer 1 in the example) to a string object before performing the concatenation operation.int one = 1; System.out.println("You're number " + one);
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.