String Handing in Java
© Oxford University Press 2018. All rights reserved.
Introduction
• Strings are treated differently in Java compared to C language;
• In the latter case, it represents an array of characters terminated
by null character.
• In Java, a string is an object of a class, and there is no automatic
appending of null character by the system.
• In Java, there are three classes that can create strings and
process them with nearly similar methods.
(i) class String
(ii) class StringBuffer
(iii) class StringBuilder
• All the three classes are part of [Link] package.
© Oxford University Press 2018. All rights reserved.
Overview of Three String Classes
• All the three classes have several constructors that can be used
for constructing strings.
• In the case of String class, an object may be created as
String str1 = “abcd”;
© Oxford University Press 2018. All rights reserved.
Overview of Three String Classes
• The aforementioned two declarations are equivalent to the
following:
char s1 *+ = ,‘a’, ‘b’, ‘c’, ‘d’-;
char s2 *+ = ,‘B’, ‘e’, ‘l’, ‘l’-;
© Oxford University Press 2018. All rights reserved.
Storage of Strings
• The objects of class String have a special storage facility, which is
not available to objects of other two String classes or to objects
of any other class.
• The memory allocated to a Java program is divided into two
segments:
(i) Stack
(ii) Heap
© Oxford University Press 2018. All rights reserved.
Storage of Strings
• The variables are stored on heap, whereas the program is stored
on stack.
• Within the heap, there is a memory segment called ‘String
constant pool’.
• The String class objects can be created in two different ways:
String strx = “abcd”;
String strz = new String(“abcd”);
© Oxford University Press 2018. All rights reserved.
Program Example
© Oxford University Press 2018. All rights reserved.
Immutability
• The string objects created by class String are immutable.
• By immutable implies that once an object is created, its value or
contents cannot be changed.
• Neither the characters in the String object once created nor their
case (upper or lower) can be changed.
• New String objects can always be created and assigned to older
String object references.
• Thus, when you change the content of a string by defining a new
string, the old and new remain in the memory.
• The immutable objects are thread safe and so are the String
objects.
© Oxford University Press 2018. All rights reserved.
Immutability
• The objects created by class StringBuffer are mutable.
• These are stored on the heap segment of memory outside the
String constant pool.
• The contents of StringBuffer strings may be changed without
creating new objects.
• The methods of StringBuffer are synchronized, and hence, they
are thread safe.
© Oxford University Press 2018. All rights reserved.
Immutability
• The objects of class StringBuilder are also mutable but are not
thread safe.
• The operations are fast as compared to StringBuffer and there is
no memory loss as is the case with String class.
• The class StringBuilder has the same methods as the class
StringBuffer.
• Therefore, if multithreads are not being used, then StringBuilder
class should be used to avoid memory loss.
© Oxford University Press 2018. All rights reserved.
Properties of String, StringBuffer, and
StringBuilder objects
© Oxford University Press 2018. All rights reserved.
Interface CharSequence
• It is an interface in [Link] package.
• It is implemented by several classes including the classes String,
StringBuffer, and StringBuilder.
It has the following four methods.
(i) charcharAt(int index): The method returns character value at specified
index value.
(ii) int length(): This method returns the length of this (invoking) character
sequence.
(iii) CharSequence subsequence(int startIndex, endIndex): The method
returns a subsequence from start index to end index of this sequence.
Throws IndexOutOfBoundsException.
(iv) String to String(): The method returns a string containing characters of
the sequence in the same.
© Oxford University Press 2018. All rights reserved.
Program Example
© Oxford University Press 2018. All rights reserved.
Class String
• The class String is used to represent strings in Java. It is declared as
public final class String
extends Object
implements serializable, comparable<String>, charSequence
• The String class is final, it cannot be extended.
© Oxford University Press 2018. All rights reserved.
Constructors of Class String
Following are the constructors of class String:
1. String()
This constructor creates a string without any characters. See the
following examples.
String str = new String();
String str1 = “”;
2. String (byte [] barray)
It constructs a new string by decoding the specified byte[] barray by
using a computer’s default character set. The following code
constructs str2 = “ABCDE”.
byte []bray = new byte[]{65, 66, 67, 68, 69};
String str2 = new String(bray);
© Oxford University Press 2018. All rights reserved.
Constructors of Class String
3. String (byte [] barray, Charset specifiedset)
It constructs a new string by decoding the specified byte array (bray)
by using specified character set.
• Some of the Charsets supported by Java are UTF8, UTF16, UTF32,
and ASCII.
• These may be written in lower case such as utf8, utf16, utf32,
and ascii.
4. String(byte[] bray, int offset, int length, String charsetName)
The constructor constructs String object by decoding the specified
part of byte array using specified Charset.
For example
String str4 = new String(bray,1, 3, “ascii”);
© Oxford University Press 2018. All rights reserved.
Constructors of Class String
5. String (byte[] barray, string charsetName}
The constructor constructs a string by decoding the byte array using
specified Charset.
String str3 = new String(bray, “UTF8”);
• The method throws UnsupportedEncodingException if the given
charset is not supported.
© Oxford University Press 2018. All rights reserved.
Program Example
© Oxford University Press 2018. All rights reserved.
Methods for Extracting Characters from Strings
© Oxford University Press 2018. All rights reserved.
Methods for Extracting Characters from Strings
The signatures of the first two methods are as:
1. char charAt (int n), where n is a positive number, which gives the
location of a character in a string.
• It returns the character at the specified index location.
• Thus, in String ‘Delhi’ the index value of ‘D’ is 0, index value of ‘e’
is 1, ‘h’ is 3, and so on.
© Oxford University Press 2018. All rights reserved.
Methods for Extracting Characters from Strings
2. void getChars (int SourceStartindex, int SourceEndindex, char
targetarray[], int targetindexstart)
• This method takes characters from a string and deposits them in
another string.
• int SourceStartindex and int SourceEndindex relate to the source
string.
• char targetarray[] relates to the array that receives the string
characters. The int targetindexstart is the index value of target
array.
© Oxford University Press 2018. All rights reserved.
Program Example
© Oxford University Press 2018. All rights reserved.
Methods for Comparison of Strings
© Oxford University Press 2018. All rights reserved.
Difference between == and Method Equals()
• The operator == simply compares the references. E.g.
if (str1==str2)
• The contents are compared by the method equals() as
if ([Link](str3))
© Oxford University Press 2018. All rights reserved.
Program Example
© Oxford University Press 2018. All rights reserved.
Program Example
© Oxford University Press 2018. All rights reserved.
Methods for Modifying Strings
The ways to modify strings are as follows:
1. Define a new string.
2. Create a new string out of substring of an existing string.
3. Create a new string by adding two or more substrings.
4. Create a new string by replacing a substring of an existing string.
5. Create a new string by trimming the existing string.
© Oxford University Press 2018. All rights reserved.
Methods for Modifying Strings
© Oxford University Press 2018. All rights reserved.
Program Example
© Oxford University Press 2018. All rights reserved.
Methods for Searching Strings
indexOf()
(i) Int indexOf(int character/substring)—searches for the first
occurrence of a specified character in the string.
(ii) int indexOf(int character/substring, int index)—searches for the
first occurrence of a specified character or substring and the
search starts from the specified index value, that is, the second
argument.
© Oxford University Press 2018. All rights reserved.
Program Example
© Oxford University Press 2018. All rights reserved.
Program Example
© Oxford University Press 2018. All rights reserved.
Class StringBuffer
It defines the strings that can be modified as well as the number of
characters that may be changed, replaced by another, a string that may
be appended, etc.
• The strings are also thread safe. For the strings created by class
StringBuffer, the compiler allocates extra capacity for 16 more
characters so that small modifications do not involve relocation of
the string.
The class is declared as follows:
public final class StringBuffer
extends Object
implements Serializable, CharSequence
© Oxford University Press 2018. All rights reserved.
Constructors of Class Stringbuffer
© Oxford University Press 2018. All rights reserved.
Program Example
© Oxford University Press 2018. All rights reserved.
Program Example
© Oxford University Press 2018. All rights reserved.