The String and StringBuffer Classes |
Literals
In the Java language, you specify literal strings between double quotes just like in C and C++.You can use literal strings anywhere you would use a String object. For example,"Hello World!"System.out.println()
accepts a String argument, so you could use a literal string in place of a String there.You can also use String methods directly from a literal string.System.out.println("And might I add that you look lovely today.");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 above construct is equivalent to, but more efficient than, this oneString s = "Hola Mundo";because the compiler ends up creating two Strings instead of one: first when the compiler encounters "Hola Mundo!", and second when it encountersString s = new String("Hola Mundo");new String()
.Concatentation and the + Operator
In the Java language, you can use '+' to concatenate Strings together.This is a little deceptive because, as you know, Strings are immutable objects; they can't be changed. However, behind the scenes the compiler uses StringBuffers to implement concatenation. The above example is compiled to:String cat = "cat"; System.out.println("con" + cat + "enation");String cat = "cat"; System.out.println(new StringBuffer.append("con").append(cat).append("enation"));
The String and StringBuffer Classes |