|
|
The String and StringBuffer Classes |
Strings and the Java Compiler
The Java compiler uses theStringandStringBufferclasses behind the scenes to handle literal strings and concatenation.Literal Strings
In Java, you specify literal strings between double quotes:You can use literal strings anywhere you would use a"Hello World!"Stringobject. For example,System.out.printlnaccepts aStringargument, so you could use a literal string in place of aStringthere.You can also useSystem.out.println("And might I add that you look lovely today.");Stringmethods directly from a literal string.Because the compiler automatically creates a newint len = "Goodbye Cruel World".length();Stringobject for every literal string it encounters, you can use a literal string to initialize aString.The above construct is equivalent to, but more efficient than, this one, which ends up creating twoString s = "Hola Mundo";Strings instead of one:The compiler creates the first string when it encounters the literal string "Hola Mundo!", and the second one when it encountersString s = new String("Hola Mundo");new String.Concatenation and the + Operator
In Java, you can use+to concatenateStrings together:This is a little deceptive because, as you know,String cat = "cat"; System.out.println("con" + cat + "enation");Strings can't be changed. However, behind the scenes the compiler usesStringBuffers to implement concatenation. The above example compiles to:You can also use theString cat = "cat"; System.out.println(new StringBuffer().append("con").append(cat).append("enation"));+operator to append values to aStringthat are not themselvesStrings:The compiler converts the non-System.out.println("Java's Number " + 1);Stringvalue (the integer1in the example) to aStringobject before performing the concatenation operation.
|
|
The String and StringBuffer Classes |