String, StringBuffer, and StringBuilder are classes present in the Object class. String objects are immutable, whereas StringBuffer and StringBuilder objects can be modified.
String Class
The String class is defined in the java.lang package, and hence it is implicitly available to all the programs in Java. The String class is declared as final, which means that it cannot be subclassed. It extends the Object class and implements the Serializable, Comparable, and CharSequence interfaces.
Java implements strings as objects of type String. A string is a sequence of characters. Unlike most of other languages, Java treats a string as a single value rather than as an array of characters.
String objects are immutable, i.e., once an object of the String class is created, the string it contains cannot be changed. In other words, once a String object is created, the characters that comprise the string cannot be changed. Whenever any operation is performed on a String object, a new String object will be created while the original contents of the object will remain unchanged. However, at any time, a variable declared as a String reference can be changed to point to some other String object.
Constructors defined in the String class: The String class defines several constructors. The most common constructor of the String class is the one given below:
public String(String value)
This constructor constructs a new String object initialized with the same sequence of the characters passed as the argument. In other words, the newly created String object is the copy of the string passed as an argument to the constructor.
Other constructors defined in the String class are as follows:
- public String()
This constructor creates an empty String object. However, the use of this constructor is unnecessary because String objects are immutable.
- public String(char[] value)
This constructor creates a new String object initialized with the same sequence of characters currently contained in the array that is passed as the argument to the constructor.
- public String(char[] value, int startindex, int len)
This constructor creates a new String object initialized with the same sequence of characters currently contained in the subarray. This subarray is derived from the character array and the two integer values that are passed as arguments to the constructor. The int variable startindex represents the index value of the starting character of the subarray, and the int variable len represents the number of characters to be used to form the new String object.
- public String(StringBuffer sbf)
This constructor creates a new String object that contains the same sequence of characters currently contained in the string buffer argument.
- public String(byte[] asciichars)
The array of bytes passed as an argument to the constructor contains the ASCII character set. Therefore, this array is first decoded using the default charset of the platform. Then the constructor creates a new String object initialized with the same sequence of characters obtained after decoding the array.
- public String(byte[] asciiChars, int startindex, int len)
This constructor creates the String object after decoding the array of bytes and by using the subarray of bytes.
New constructors in J2SE 5: Two new constructors have been added to Java in version 5, which are as follows:
- String(int code Points[], int startindex, int numchars)
where code Points is an array that returns integers and contains Unicode code points, startindex is an integer that represents starting index, and numchars is the number of characters in the string.
- String(StringBuilder strBldObj)
This constructor uses a StringBuilder object as an argument.
Special String Operations
- Finding the length of string
The String class defines the length() method that determines the length of a string. The length of a string is the number of characters contained in it. The signature of the length() method is as follows:
public int length()
- String Concatenation using the + operator
The + operator is used to concatenate two strings, producing a new String object as the result. For example:
String sale = “500″;
String s = “Our daily sale is” + sale + “dollars”;
System.out.println(s);This code will display the string “Our daily sale is 500 dollars”.
The + operator can also be used to concatenate a string with other data types. For example:
int sale = 500;
String s = “Our daily sale is” + sale + “dollars”;
System.out.println(s);This code will display the string “Our daily sale is 500 dollars”. In this case, the variable sale is declared as int rather than String, but the output produced is the same. This is because the int value contained in the variable sale is automatically converted to String type, and then the + operator concatenates the two strings.
String Comparison
The String class defines various methods that are used to compare strings or substrings within strings. Each of them is discussed in the following sections:
- equals()
The equals() method is used to check whether the Object that is passed as the argument to the method is equal to the String object that invokes the method. It returns true if and only if the argument is a String object that represents the same sequence of characters as represented by the invoking object. The signature of the equals() method is as follows:
public boolean equals(Object str)
- equalsIgnoreCase()
The equalsIgnoreCase() method is used to check the equality of the two String objects without taking into consideration the case of the characters contained in the two strings. It returns true if the two strings are of the same length and if the corresponding characters in the two strings are the same, without considering the case. The signature of the equalsIgnoreCase() method is as follows:
public boolean equalsIgnoreCase(Object str)
- compareTo()
The compareTo() method is used in conditions where a Programmer wants to sort a list of strings in a predetermined order. The compareTo() method checks whether the string passed as an argument to the method is less than, greater than, or equal to the invoking string. A string is considered less than another string if it comes before it in alphabetical order. The signature of the compareTo() method is as follows:
public int compareTo(String str)
where, str is the String being compared to the invoking String. The compareTo() method returns an int value as the result of String comparison. The meaning of these values are given in the following table:
Value Meaning Less than zero The invoking string is less than the argument string. Zero The invoking string and the argument string are same. Greater than zero The invoking string is greater than the argument string. The String class also has the compareToIgnoreCase() method that compares two strings without taking into consideration their case difference. The signature of this method is given below:
public int compareToIgnoreCase(String str)
- regionMatches()
The regionMatches() method is used to check the equality of two string regions where the two string regions belong to two different strings. The signature of the method is given below:
public boolean regionMatches(int startindex, String str2, int startindex2, int len)
There is also an overloaded version of the method that tests the equality of the substring ignoring the case of characters in the substring. Its signature is given below:
public boolean regionMatches(boolean ignoreCase, int startindex, String str2, int startindex2, int len)
In both signatures of the method, startindex specifies the starting index of the substring within the invoking string. The str2 argument specifies the string to be compared. The startindex2 specifies the starting index of the substring within the string to be compared. The len argument specifies the length of the substring being compared. However, in the latter signature of the method, the comparison is done ignoring the case of the characters in the substring only if the ignoreCase argument is true.
- startsWith()
The startsWith() method is used to check whether the invoking string starts with the same sequence of characters as the substring passed as an argument to the method. The signature of the method is given below:
public boolean startsWith(String prefix)
There is also an overloaded version of the startsWith() method with the following signature:
public boolean startsWith(String prefix, int startindex)
In both signatures of the method given above, the prefix denotes the substring to be matched within the invoking string. However, in the second version, the startindex denotes the starting index into the invoking string at which the search operation will commence.
- endsWith()
The endsWith() method is used to check whether the invoking string ends with the same sequence of characters as the substring passed as an argument to the method. The signature of the method is given below:
public boolean endsWith(String prefix)
Modifying a String
The String objects are immutable. Therefore, it is not possible to change the original contents of a string. However, the following String methods can be used to create a new copy of the string with the required modification:
- substring()
The substring() method creates a new string that is the substring of the string that invokes the method. This method has two forms:
public String substring(int startindex)
public String substring(int startindex, int endindex)
where, startindex specifies the index at which the substring will begin and endindex specifies the index at which the substring will end. In the first form where the endindex is not present, the substring begins at startindex and runs till the end of the invoking string.
- Concat()
The concat() method creates a new string after concatenating the argument string to the end of the invoking string. The signature of the method is given below:
public String concat(String str)
- replace()
The replace() method creates a new string after replacing all the occurrences of a particular character in the string with another character. The string that invokes this method remains unchanged. The general form of the method is given below:
public String replace(char old_char, char new_char)
- trim()
The trim() method creates a new copy of the string after removing any leading and trailing whitespace. The signature of the method is given below:
public String trim(String str)
- toUpperCase()
The toUpperCase() method creates a new copy of a string after converting all the lowercase letters in the invoking string to uppercase. The signature of the method is given below:
public String toUpperCase()
- toLowerCase()
The toLowerCase() method creates a new copy of a string after converting all the uppercase letters in the invoking string to lowercase. The signature of the method is given below:
public String toLowerCase()
Searching Strings
The String class defines two methods that facilitate in searching a particular character or sequence of characters in a string. They are as follows:
- IndexOf()
The indexOf() method searches for the first occurrence of a character or a substring in the invoking string. If a match is found, then the method returns the index at which the character or the substring first appears. Otherwise, it returns -1. The indexOf() method has the following signatures:
public int indexOf(int ch)
public int indexOf(int ch, int startindex)
public int indexOf(String str)
public int indexOf(String str, int startindex)
- lastIndexOf()
The lastIndexOf() method searches for the last occurrence of a character or a substring in the invoking string. If a match is found, then the method returns the index at which the character or the substring last appears. Otherwise, it returns -1. The lastIndexOf() method has the following signatures:
public int lastIndexOf(int ch)
public int lastIndexOf (int ch, int startindex)
public int lastIndexOf (String str)
public int lastIndexOf (String str, int startindex)
StringBuffer and StringBuilder classes
Like the String class, the StringBuffer and StringBuilder classes are also present in the java.lang package. Therefore, they are implicitly available to all java classes.
StringBuilder is a new concept introduced in J2SE 5. It is very similar to StringBuffer class. Like String and StringBuffer it extends directly from Object class. StringBuilder can act as a replacement of StringBuffer in places where it is not multithreaded environment. That is where we are not worried about Synchronization or multithreading. The signature of StringBuilder is public final class StringBuilder extends Object implements Serializable, CharSequence. Because StringBuilder is not synchronized, it offers faster performance than StringBuffer.
Constructors defined in the StringBuffer class: The StringBuffer class defines several constructors. The most common constructor of the StringBuffer class is the one given below:
- public StringBuffer(String value)
This will construct a StringBuffer constructor with contents of string value and reserves space for extra 16 characters.
Other constructors defined in the StringBuffer class are as follows:
- StringBuffer()
This will construct a default StringBuffer constructor reserving room for 16 characters.
- StringBuffer(int size)
This will create a constructor with a specified initial size.
- StringBuffer(Charsequence ch)
This will create a constructor with a charactersequence ch.
Special StringBuffer Operations
- Length of StringBuffer
The StringBuffer and StringBuilder classes define the length() method that determines the length of a StringBuffer/StringBuilder. The length of a Stringbuffer is the number of characters contained in the StringBuffer. The signature of the length() method is given below:
public int length()
Length of a StringBuffer can be set using the setLength() method.
public void setLength(int len)
where len is the specified length of the StringBuffer. It is an integer value, and is always non-negative.
- Capacity of StringBuffer
The StringBuffer and StringBuilder classes define the capacity() method that determines the capacity of a StringBuffer/StringBuilder. The capacity of a StringBuffer is the maximum number of characters that a StringBuffer can hold. The signature of the capacity() method is given below:
public int capacity ()
Capacity of a pre-constructed StringBuffer can be pre-allocated using the ensureCapacity() method of StringBuffer as:
public void ensureCapacity (int capacity)
- Finding character at a specified location
The StringBuffer and StringBuilder classes define the charAt() method that is used to obtain the character at a specified index in the StringBuffer/StringBuilder.
char charAt(int index)
A character at a given index can be set using setCharAt (int index,char ch) method of StringBuffer class.
For both the above methods, index cannot be a negative value.
- Appending to a StringBuffer
public StringBuilder append(char c)
This method of StringBuffer class appends the string representation of the char argument to the current sequence. The argument is appended to the contents of this sequence. This increases the length of the sequence by 1.
- Inserting in a StringBuffer
StringBuffer has methods to insert various datatypes like a character a string, a string representation of float, double etc at a specified index.
public StringBuilder insert(int offset, char c)This method will insert the string representation of the char argument into this sequence.
The second argument is inserted into the contents of this sequence at the position indicated by offset. The length of this sequence increases by one.public StringBuilder insert(int offset, char[] str)
This method will insert the string representation of the char array argument into this sequence.
The characters of the array argument are inserted into the contents of this sequence at the position indicated by offset. The length of this sequence increases by the length of the argument.public StringBuilder insert(int dstOffset, CharSequence s)
This method will insert the specified CharSequence into this sequence.
The characters of the CharSequence argument are inserted, in order, into this sequence at the indicated offset, moving up any characters originally above that position and increasing the length of this sequence by the length of the argument s.In addition, there are insert methods with argument as an integer value, a boolean value, a long, a float, and a double.
- Reversing the character sequence of a StringBuffer
The StringBuffer class has a method to reverse the character sequence in a StringBuffer.
public StringBuffer reverse()
This will cause the character sequence to be replaced by the reverse of the sequence.
- Replacing a sequence of character with another sequence.
public StringBuilder replace(int start, int end, String str)
This will replace the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end – 1 or to the end of the sequence if no such character exists.
- Deleting a character
The delete() method of StringBuffer class is used to delete a character from starting to the end as specified. There is another method called deleteCharAt () used to delete char from a specified index.
public StringBuffer delete(int start, int end)
public StringBuffer deleteCharAt(int index)
- Obtaining a substring
StringBuffer class has a method to obtain a substring from a given string. The substring starts from the index specified, and extends up to the end of StrigBuffer. There is also a method with starting and ending indexes specified.
public String subString(int startindex)
This will extract a substring from specified index startindex and extends up to end of the StringBuffer.
public String subString(int startindex, int endindex)
This will extract a substring from specified index startindex and extends up to specified index endindex.
- Finding an index
The StringBuffer class has methods for finding indexes of first and last occurrence of a specified string within the StringBuffer.
public int indexOf(String str)
If the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
public int indexOf(String str, int fromIndex)
This will return the index within this string of the first occurrence of the specified substring, starting at the specified index. If the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
public int lastIndexOf(String str)
If the string argument occurs as a substring within this object, then the index of the first character of the last such substring is returned; if it does not occur as a substring, -1 is returned.
public int lastIndexOf(String str, int fromIndex)
This will return the index within this string of the last occurrence of the specified substring, starting at the specified index. If the string argument occurs as a substring within this object, then the index of the first character of the last such substring is returned; if it does not occur as a substring, -1 is returned.
- Conversion to string
A StringBuffer is converted to a string using the toString method.
public String toString()
This will return a string representing the data in this sequence. A new String object is allocated and initialized to contain the character sequence currently represented by this object. This String is then returned. Subsequent changes to this sequence do not affect the contents of the String.
- Changing the size
StringBuffer class has a method called trimToSize, used to reduce the size of the character buffer for the invoking object to exactly fit the current contents.
public void trimToSize()
If the buffer is larger than necessary to hold its current sequence of characters, it can be resized to become more space efficient.
- Get certified in first attempt download master-ciw-enterprise-developer - Master CIW Enterprise Developer simulation.
- Get certified in first attempt download scbcd - SCBCD simulation.
- Best exam simulation SUN scdjws download free trial.
- Become SUN SCJP certified.
- Best exam simulation SUN scjp-5-0 download free trial.
- Get certified in first attempt download scmad - SCMAD simulation.
- Click here to download scwcd test study guide and practice question.
- Become SUN Java 5.0 certified.
- Best exam simulation SUN CX310-056 download free trial.
- Download practice question and study guide for CX310-065 for exam.
- Click here to download CX310-066 test study guide and practice question.
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.