Previous Page Next Page Start of Tutorial > Start of Trail > Start of Lesson Lesson Contents

Trail:
Essential Java Classes
Lesson:
The String and StringBuffer Classes



Help on searching
is available.

Search technology
by Excite, Inc.

Strings and the Java Compiler

The Java compiler uses the String and StringBuffer classes behind the scenes to handle literal strings and concatenation.

Literal Strings

In Java, 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 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, which ends up creating two Strings instead of one:
String s = new String("Hola Mundo");
The compiler creates the first string when it encounters the literal string "Hola Mundo!", and the second one when it encounters new String.

Concatenation and the + Operator

In Java, 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 can't be changed. However, behind the scenes the compiler uses StringBuffers to implement concatenation. The above example compiles to:
String cat = "cat";
System.out.println(new StringBuffer().append("con").append(cat).append("enation"));
You can also use the + operator to append values to a String that are not themselves Strings:
System.out.println("Java's Number " + 1);
The compiler converts the non-String value (the integer 1 in the example) to a String object before performing the concatenation operation.
 
Previous Page Next Page Start of Tutorial > Start of Trail > Start of Lesson Lesson Contents

Michel RIVEILL

Laboratoire I3S - Bât. ESSI
930 Route des Colles
06903 Sophia Antipolis CEDEX

email : riveill at unice.fr

Généralité

Projet Rainbow

Ressources en lignes

Les rubriques des cours :

 

Rechercher sur ce site avec Google

 

dernière mise à jour
le 18 septembre 2003

 

 

Réservation d'Hôtel à Prix Réduits - HotelClub