Previous | Next | Trail Map | Writing Java Programs | The String and StringBuffer Classes


Strings and the Java Compiler

Literals

In the Java language, you specify literal strings between double quotes just like in C and C++.
"Hello World!"
You can use literal strings anywhere you would use a String object. For example, System.out.println() accepts a String argument, so you could use a literal string in place of a String there.
System.out.println("And might I add that you look lovely today.");
You can also use String methods directly from a literal string.
int len = "Goodbye Cruel World".length();
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.
String s = "Hola Mundo";
The above construct is equivalent to, but more efficient than, this one
String s = new String("Hola Mundo");
because the compiler ends up creating two Strings instead of one: first when the compiler encounters "Hola Mundo!", and second when it encounters new String().

Concatentation and the + Operator

In the Java language, you can use '+' to concatenate Strings together.
String cat = "cat";
System.out.println("con" + cat + "enation");
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(new StringBuffer.append("con").append(cat).append("enation"));


Previous | Next | Trail Map | Writing Java Programs | The String and StringBuffer Classes