8.8. Strings

In Java, strings are real objects, members of the java.lang.String class. However, because they are so frequently used, you are allowed to create them simply by using double quotes, as follows:

String s1 = "This is a String";

The normal object-creation approach of using new is legal also, for example,

String s2 = new String("This is a String too");

but is rarely used.

The most unusual thing about the String class is that strings are immutable; once created they cannot be changed. “Hold on,” you say, “I know there is no setCharacterAt method, but I've seen string concatenation used lots of places.” That's a good point; the + character can be used to concatenate strings, as follows:

String test = "foo" + "bar"; // "foobar"

Get Core Web Programming, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.