The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

Strings and the Compiler

The compiler uses the String and the StringBuffer classes behind the scenes to handle literal strings and concatenation. As you know, you specify literal strings between double quotes:
"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 there:
System.out.println("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 preceding construct is equivalent to, but more efficient than, this one, which ends up creating two identical strings:
String s = new String("Hola Mundo"); //don't do this
You can use + to concatenate strings:
String cat = "cat";
System.out.println("con" + cat + "enation");
Behind the scenes, the compiler uses string buffers to implement concatenation. The preceding example compiles to:
String cat = "cat";
System.out.println(new StringBuffer().append("con").
append(cat).append("enation").toString());
You can also use the + operator to append to a string values that are not themselves strings:
System.out.println("You're number " + 1);
The compiler implicitly converts the nonstring value (the integer 1 in the example) to a string object before performing the concatenation operation.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.