The String Class (Exam Objective 3.1)
413
the skimpy 7 or 8 bits that ASCII provides), a rich, international set of characters iseasily represented in Unicode.In Java, strings are objects. Just like other objects, you can create an instance of aString with the
new
keyword, as follows:
String s = new String();
This line of code creates a new object of class String, and assigns it to thereference variable
s
. So far, String objects seem just like other objects. Now, let'sgive the String a value:
s = "abcdef";
As you might expect, the String class has about a zillion constructors, so you canuse a more efficient shortcut:
String s = new String("abcdef");
And just because you'll use strings all the time, you can even say this:
String s = "abcdef";
There are some subtle differences between these options that we'll discuss later,but what they have in common is that they all create a new String object, with avalue of
"abcdef"
, and assign it to a reference variable
s
. Now let's say that youwant a second reference to the String object referred to by
s
:
String s2 = s; // refer s2 to the same String as s
So far so good. String objects seem to be behaving just like other objects, sowhat's all the fuss about?…Immutability! (What the heck is immutability?) Onceyou have assigned a String a value, that value can never change— it's immutable,frozen solid, won't budge, fini, done. (We'll talk about why later, don't let us forget.)The good news is that while the String object is immutable, its reference variable isnot, so to continue with our previous example:
s = s.concat(" more stuff"); // the concat() method 'appends'// a literal to the end