1. String Class

  • String, for constant strings.

  • StringBuffer, for strings that can change.

Why use String? Because they are constants, Strings are cheaper than StringBuffers and they can be shared.

StringBuffer dest = new StringBuffer(len);
StringBuffer dest = new StringBuffer();

String dest = new String("Destination");

1.3. String literals

"Gobbledy gook."

is equivalent to:

new String("Gobbledy gook.")
charAt()

Figure 5.1. charAt() Method

charAt() Method

and

length()
append()

Figure 5.2. Inside the StringBuffer

Inside the StringBuffer

toString();

All classes inherit toString() from the Object class and many classes override this method to provide an implementation that is meaningful to that class. Implement it in your classes too!

valueOf()

Static member of String that can be used to convert variables of different types to Strings.

Audio in Portuguese

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

1.7.1. Literal Strings

"Hello World!"

You can use literal strings anywhere you would use a String object.

System.out.println("I add that you look lovely today.");
int len = "Goodbye Cruel World".length();
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");

1.7.2. Concatenation and the + Operator

String cat = "cat";
System.out.println("con" + cat + "enation");

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);
[Caution]Caution

Java Strings are First-class Objects, unlike C or C++ strings which are simply null-terminated arrays of 8-bit characters.

Audio in Portuguese