Contents

String Class

To work with strings, Java provides three final classes String,
StringBuffer and
StringBuilder. In this chapter, we will look more deeply at the most commonly
used methods provided by these classes.String class is provided in java.lang package. It provides various constructors
and methods to create and manipulate String objects. Objects of String class are
immutable, i.e., once the object has been created and initialized, it can not be
changed later. Every method in the class that appears to modify the contents of
a String object, actually creates a new object having modifi ed contents and the
existing object becomes unreferenced.

Creating String Objects

A String object can be created using:

String literals

Constructor functions

1)Using String Literals
Using a string literal is the easiest way to create String object.
As shown below:

String str1 = “HELLO”;

The above statement creates a String class object having “HELLO” and its
reference is assigned to str1 reference variable. As shown below:

If you assign a new string literal to reference variable: str1, a new object will be
created and the existing object becomes unreferenced. As shown below:

Operators + and += can also be used to create String objects. Java does not provide
operator overloading like C++ but + and += operators are already overloaded in
Java for String class only.
For example:

String st1 = “REAL”;
String st2 = st1 + “ JAVA”;

As a result, a new object will be created having contents “REAL JAVA”, as shown
below:

Consider the following code:

String st3 = “HELLO”;
st3 += “ JAVA”;

Since String objects are immutable, now reference variable
st3 will refer to
new object having “HELLO JAVA” and the existing object becomes eligible for
garbage collection, as shown follows:

2)Using Constructor Functions
The String class provides the following commonly used constructors:

String( )

This constructor creates an object which is initialized to empty.

String(String object)

It creates an object having contents same as the String object passed as
argument.For example:

This constructor consists of three parameters:char [ ] ary: Specifi es the array as source of character to be copied in the new object.int startIndex: Specifi es the index value from where to start int count: Specifi es the number of characters to be copied.For example:

Using String Class Methods

String toUpperCase( )

String toLowerCase( )

The method toUpperCase()converts lower case characters to upper case and
toLowerCase()converts characters to lower case. If none of the characters are
changed, both methods return reference to the same String object, otherwise
returns new String object. For example:

This method copy characters from String object into an array of characters.
It starts reading characters from specifi ed startIndx to endIndx-1. These are
copied in destination (dest) array starting at
desStartIndx.For Example:

This method returns true if the length of the string is zero(0)
else return false.For Example:

String s = “James Gosling”;
System.out.println(s.isEmpty());

int compareTo(String object)

This method compares the contents of invoking string object with the string
object passed as argument. Characters are compared lexicographically. It
returns a value +ve, -ve zero. The zero(0) value means both strings are same.
The +ve value means that the invoking object is lexicographically greater than the other string The -ve value means that the invoking string object is lexicographicall less than the other string object. For Example:

The above code prints -1 (ASCII of ‘A’ - ASCII of ‘B’) which means that
s1 is less than s2.
The above code prints 1 (ASCII of ‘B’ - ASCII of ‘A’), which means that
s2 is greater than s1.
The following program sorts a list of strings using compareTo() method:

The equals()method is a member of java.lang.Object
class. It basically
checks the reference equality but java.lang.Stringclass override this method
for content equality. If the contents are same than it returns true else false.For Example:

In the above code, s3 refers to a new string object containing the contents of s1
and s2 objects,
s1.concat(s2)
creates a new string object containing “RealJava” but
its reference will not be stored anywhere, however, the contents of object s1remain same (“Real”) due to immutable nature of string objects.
But,If we write: s1 = s1.concat(s2); then it generates new string object containing “RealJava” and its
reference will be stored in s1. As shown below:

String trim()

This method removes spaces from the front and the end of a string.For Example:

java.lang.StringBuffer & StringBuilder Classes

The StringBuffer and StringBuilderclasses are like String class, but their
objects are mutable, i.e., their contents can be modifi ed through certain method
calls.
Overloaded forms of insert() and append() methods, provided in these classes
make them more useful when regular changes are to be made in the character
sequence. Its append() method adds characters at the end of the string and insert()method adds characters at the specifi ed index.
The StringBuff er class is a thread safe class. The methods of this class are
synchronized, whereas StringBuilder class is not thread safe. The StringBuilder
class should be preferred over StringBuff er class because it is faster than as it
does not perform synchronization.

StringBuilder Constructors

StringBuilder()

It constructs an object without characters in it but creates an array of characters (char[] value) having room for 16 characters. A
StringBuilder object also consists of a variable count, that tracks the number
of characters the array consists of. It takes zero value by default. The value of
count variable increases as the characters are inserted or appended in the array
of characters (char[] value).

StringBuilder(int length)

It constructs an object without contents. The initial capacity is set to the length passed as argument.

StringBuilder(String str)

It constructs an object initialized to the contents of the specifi ed String argument. The initial capacity will be the length of String argument plus 16.For Example:

StringBuilder s = new StringBuilder(“SST”);

The initial capacity of object will be 19(3 + 16).

StringBuilder Methods

StringBuilder class provides some new methods to append, insert and delete
characters in existing StringBuilder objects, which is not possible with String objects.

Appending Characters:

StringBuilder class provides various overloaded forms of append() method to add characters at the end of the array of characters.

Creating String object from StringBuilder object:

The characters of StringBuilder object can be copied to String object using
toString()method. The toString()method is also overridden in StringBuilder
class. It returns a String object containing contents from
StringBuilder object.

Using equals( ) with StringBuilder objects:

StringBuilder class does not override equals()
method to match the characters
of two objects. Therefore equals() method of StringBuilder
objects checks the
reference equality and not the content equality. So the contents of
StringBuilder
object should be converted to String object using
toString() method.
For Example:

17 Years experience in Training & Development.
Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android. If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email :[email protected]#Contact : 98722-46056