12/15/2008

String objects

The String class

Be aware of where an object refers.

String a = "Bob";
String b = "Jack";
System.out.println(a);
a = b;
System.out.println(b);

<Result>

Bob
Jack

String objects are immutable
Sample
String a = "Bob";
a.concat(" Cruise");
System.out.println(a);

Result
Bob

You cannot change the String object ‘a’ refers to.

Sample
String a = "Bob";
a = a.concat(" Cruise");
System.out.println(a);

A new object is substituted for what ‘a’ referred to.


Result
Bob Cruise
_________

The StringBuilder class

The StringBuilder class is similar to the StringBuffer class, but the StringBuilder class is faster than the StringBuffer class in almost every aspect
When you connect strings it is better to use the StringBuilder class.
Sample
StringBuilder a = new StringBuilder("Bob");
a.append(" Cruise");
System.out.println(a);

Result
Bob Cruise
You can append, replace, insert another string to the StringBuilder object ‘a’ refers to.