Java strings

Strings in Java are class objects and implemented using three classes, namely, String, StringBuffer, and StringBuilder. A Java string is an instantiated object of the above classes. Unlike C, a Java string is not a character array and is not NULL terminated. 

 

1. String class

String class is immutable, i.e., once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class can extend it. This class differs from other classes, one difference being that the String objects can be used with the += and “+” operators for concatenation.

Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing whether two Strings contain the same value. The substring( ) method is used to obtain a selected portion of a String.

1.1 String object creation

String objects may be declared and created using “new” operator as follows:

String str = new String("Sample String"); // Option 1: using "new" operator

A string object can also be created using a string literal enclosed inside double quotes as shown:

String str = "Sample String";  // Option 2: using string literal

 

Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of a string literal can be assigned to another String reference. If two or more Strings have the same set of characters in the same sequence then they share the same reference in memory. Below illustrates this phenomenon.

ComparisonTest.java

public class ComparisonTest {    

public static void main(String[] args) {
String str1 = "My name is TechGuru";
String str2 = "My name is TechGuru";
String str3 = "My name "+ "is TechGuru";
String name = "TechGuru";
String str4 = "My name is " + name;
String str5 = new String("My name is TechGuru");

System.out.println("String comparison using the equals() method");
System.out.println(str1.equals(str2)); //true 
System.out.println(str1.equals(str3)); //true 
System.out.println(str1.equals(str4)); //true 
System.out.println(str1.equals(str5)); //true 

System.out.println("\nString comparison using the == operator");
System.out.println(str1==str2); //true
System.out.println(str1==str3); //true
System.out.println(str1==str4); //false
System.out.println(str1==str5); //false
}
}

 

Output:

String comparison using the equals() method
true
true
true
true

String comparison using the == operator
true
true
false
false

In the above code, all the five String references are same, as because they are equal content-wise. It can be tested by using the equals() method. This method returns true when two String objects hold the same content (i.e. the same values). The output of the program also support this.

The String references str1, str2 and str3 denote the same String object, initialized with the string literal: “My name is TechGuru“. But the Strings str4 and str5 denote new String objects. Using “==” relational operator we can test this. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false.

 

Constructing String objects can also be done from array of bytes, array of characters, or string itself.

byte[] bytes = {0, 2, 4, 6, 8};  // byte array         
char[] characters = {'a', 'b', 'C', 'D'}; // char array
String str = new String("pqrst"); // string object

// Examples of Creation of Strings
String byteStr = new String(bytes);
String charStr = new String(characters);
String newStr = new String(str);

NOTE: A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (“”), using the string concatenation operator (+).

 

1.2 Java String Methods

The important methods of the String class are as follows:

1. public int compareTo (String anotherString)
Compares two strings lexicographically.

2. public char charAt (int index)
Returns the character at the specified index.

3. public void getChars (int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.

4. public int length()
Returns the length of this string.

5. public boolean equals (Object anObject)
Compares this string to the specified object.

6. public boolean equalsIgnoreCase (String anotherString)
Compares this String to another String, ignoring case considerations.

7. public String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.

7. public String toLowerCase()
Converts all of the characters in this String to upper case using the rules of the default locale.

9. public String concat(String str)
Concatenates the specified string to the end of this string.

10. public int indexOf(int ch)

Returns the index within this string of the first occurrence of the specified character.

11. public int indexOf(int ch, int fromIndex)

Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

12. public int indexOf(String str)

Returns the index within this string of the first occurrence of the specified substring.

13. public int indexOf(String str, int fromIndex)

Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

14. public int lastIndexOf(int ch)

Returns the index within this string of the last occurrence of the specified character.

15. public int lastIndexOf(int ch, int fromIndex)

Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

16. public int lastIndexOf(String str)

Returns the index within this string of the rightmost occurrence of the specified substring.

17. public int lastIndexOf(String str, int fromIndex)

Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

18. public String substring(int beginIndex)

Returns a new string that is a substring of this string.

19. public String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

20. public String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

21. public String trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

22. public String toString()

This object (which is already a string!) is itself returned.

 

The following program explains the usage of the some of the basic methods of String class.

StringsDemo.java

public class StringsDemo {

public static void main(String[] args) {
String str1 = "My name is som";
int n = str1.length();
char str2[] = new char[n];
String str3 = "som";
String str4 = "ron";
String str5 = "SoM";
String str6 = "som";
System.out.println("Length of the String str1 : " + str1.length());
System.out.println("Character at position 3 is : " + str1.charAt(3));

str1.getChars(0, n, str2, 0);
System.out.print("The String str2 is : ");
for (int i = 0; i < str2.length; i++) {
System.out.print(str2[i]);
}
System.out.println();

System.out.print("Comparision Test : ");
if (str3.compareTo(str4) < 0) {
System.out.print(str3 + " < " + str4);
} else if (str3.compareTo(str4) > 0) {
System.out.print(str3 + " > " + str4);
} else {
System.out.print(str3 + " equals " + str4);
}
System.out.println();

System.out.print("Equals Test -> ");
System.out.println("str3.equalsIgnoreCase(5) : " + str3.equalsIgnoreCase(str5));
System.out.println("str3.equals(6) : " + str3.equals(str6));
System.out.println("str1.equals(3) : " + str1.equals(str3));

str5.toUpperCase(); //Strings are immutable
System.out.println("str5 : " + str5);
String temp = str5.toUpperCase();
System.out.println("str5 Uppercase: " + temp);
temp = str1.toLowerCase();
System.out.println("str1 Lowercase: " + str1);
System.out.println("str1.concat(str4): " + str1.concat(str4));

String str7temp = " \t\n Now for some Search and Replace Examples ";
String str7 = str7temp.trim();
//str = Now for some Search and Replace Examples
System.out.println("str7 : " + str7);
String newStr = str7.replace('s', 'T');
System.out.println("newStr : " + newStr);

System.out.println("indexof Operations on Strings");
System.out.println("Index of p in " + str7 + " : " + str7.indexOf('p'));
System.out.println("Index of for in " + str7 + " : " + str7.indexOf("for"));
System.out.println("str7.indexOf('p', 30) : " + str7.indexOf('p', 30));
System.out.println("str7.indexOf(for, 30) : " + str7.indexOf("for", 30));

System.out.println("str7.lastIndexOf('p') : " + str7.lastIndexOf('p'));
System.out.println("str7.lastIndexOf('p', 4) : " + str7.lastIndexOf('p', 4));
System.out.println("str7.lastIndexOf('p', 38) : " + str7.lastIndexOf('p', 38));
System.out.println("str7.lastIndexOf(for, 4) : " + str7.lastIndexOf("for", 10));

System.out.print("SubString Operations on Strings");
String str8 = "SubString Example";
String sub5 = str8.substring(5); // "ring Example"
String sub3_6 = str8.substring(3, 6); // "Str"
System.out.println("str8 : " + str8);
System.out.println("str8.substring(5) : " + sub5);
System.out.println("str8.substring(3,6) : " + sub3_6);
}
}

 

Output:

Length of the String str1 : 14
Character at position 3 is : n
The String str2 is : My name is som
Comparision Test : som > ron
Equals Test -> str3.equalsIgnoreCase(5) : true
str3.equals(6) : true
str1.equals(3) : false
str5 : SoM
str5 Uppercase: SOM
str1 Lowercase: My name is som
str1.concat(str4): My name is somron
str7 : Now for some Search and Replace Examples
newStr : Now for Tome Search and Replace ExampleT
indexof Operations on Strings
Index of p in Now for some Search and Replace Examples : 26
Index of for in Now for some Search and Replace Examples : 4
str7.indexOf('p', 30) : 36
str7.indexOf(for, 30) : -1
str7.lastIndexOf('p') : 36
str7.lastIndexOf('p', 4) : -1
str7.lastIndexOf('p', 38) : 36
str7.lastIndexOf(for, 4) : 4
SubString Operations on Stringsstr8 : SubString Example
str8.substring(5) : ring Example
str8.substring(3,6) : Str

 

 

2. StringBuffer class

StringBuffer class is a mutable class unlike the String class which is immutable. The objects of StringBuffer class can be changed dynamically both in terms of its length and content. StringBuffer objects are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc). Strings can be obtained from StringBuffer objects. Since the StringBuffer class does not override the equals() method from the Object class, contents of StringBuffer objects should be converted to String objects for string comparison.

2.1 StringBuffer Constructors

The following example shows creation of strings using StringBuffer Constructors. We can use the capacity() method of StringBubber to know the capacity of its objects. See the program below.

StringBufferDemo.java

public class StringBufferDemo {

public static void main(String[] args) {
// Use different StringBuffer Contructors to create objects
StringBuffer strBuf1 = new StringBuffer("TechGuru");
StringBuffer strBuf2 = new StringBuffer(100); // With capacity 100
StringBuffer strBuf3 = new StringBuffer(); // Default Capacity 16

System.out.println("strBuf1 : " + strBuf1);
// capacity() returns the current capacity of StringBuffer object
System.out.println("strBuf1 capacity : " + strBuf1.capacity());
System.out.println("strBuf2 capacity : " + strBuf2.capacity());
System.out.println("strBuf3 capacity : " + strBuf3.capacity());
System.out.println("strBuf1 length : " + strBuf1.length()); // Similar to String class
System.out.println("strBuf1 charAt 2 : " + strBuf1.charAt(2)); // Similar to String class
}
}

Output:

strBuf1 : TechGuru
strBuf1 capacity : 24
strBuf2 capacity : 100
strBuf3 capacity : 16
strBuf1 length : 8
strBuf1 charAt 2 : c

 

2.2 Java StringBuffer Methods

The important methods of the StringBuffer class are as follows:

1. public int capacity()
Returns the current capacity of the StringBuffer object.

2. public int length()
Returns the length (character count) of this StringBuffer object.

3. public int charAt(int index)
The specified character of the sequence currently represented by the StringBuffer object, as indicated by the index argument, is returned.

4. public void setCharAt(int index, char ch)
The character at the specified index of this StringBuffer object is set to ch

5. public String toString()
Converts to a string representing the data in this StringBuffer object

6. public StringBuffer insert(int offset, char c)
Inserts the string representation of the char argument into this StringBuffer object.
Note that the StringBuffer class has got many overloaded ‘insert()’ methods which can be used based on the application need.

7. public StringBuffer delete(int start, int end)
Removes the characters in a substring of this StringBuffer object

8. public StringBuffer replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer object with characters in the specified String.

9. public StringBuffer reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.

10. public StringBuffer append(String str)
Appends the string to this StringBuffer object.

Note that the StringBuffer class has got many overloaded ‘append()’ methods which can be used based on the application need.

11. public void setLength(int newLength)
Sets the length of this StringBuffer object.

 

The following program explains the usage of the some of the basic methods of StringBuffer class.

StringBufferMethodsDemo.java

public class StringBufferMethodsDemo {

public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Object Programming languages");
System.out.println("Original String = " + sb);
System.out.println("Length = " + sb.length());
System.out.println("Capacity = " + sb.capacity());

// Accessing characters in a string
for (int i = 0; i < sb.length(); i++) {
System.out.print(sb.charAt(i)+ ",");
}
System.out.println();

// Inserting a string in the middle
int pos = sb.indexOf(" Programming");
sb.insert(pos, " Oriented");
System.out.println("Modified String = " + sb);

// Setting a character to a specified position
sb.setCharAt(6, '-');
System.out.println("String now = " + sb);

// Appending a string
sb.append(" are very popular.");
System.out.println("Appended String = " + sb);

// Deletion and insertion example w.r.t a character
StringBuffer sb1 = sb;
sb1.deleteCharAt(6);
sb1.insert(6, ' ');
System.out.println("New String = " + sb1);

// Deleting the characters in a substring of this sequence
sb.delete(1, 7);
System.out.println("Deleted String1 = " + sb);
sb.delete(2, 10);
System.out.println("Deleted String2 = " + sb);
sb.delete(3, 13);
System.out.println("Deleted String3 = " + sb);

// Converting StringBuffer object to String object
String s = sb.toString();
System.out.println("Converted String = " + s);

// Reversing the contents of StringBuffer object
sb.reverse();
System.out.println("Reverse String = " + sb);

sb.setLength(0);
System.out.println("Final String = " + sb);
}
}

 

Output:

Original String = Object Programming languages
Length = 28
Capacity = 44
O,b,j,e,c,t, ,P,r,o,g,r,a,m,m,i,n,g, ,l,a,n,g,u,a,g,e,s,
Modified String = Object Oriented Programming languages
String now = Object-Oriented Programming languages
Appended String = Object-Oriented Programming languages are very popular.
New String = Object Oriented Programming languages are very popular.
Deleted String1 = OOriented Programming languages are very popular.
Deleted String2 = OOProgramming languages are very popular.
Deleted String3 = OOP languages are very popular.
Converted String = OOP languages are very popular.
Reverse String = .ralupop yrev era segaugnal POO
Final String =

NOTE: A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in StringBuffer object manipulations.

 

♦ Difference between String and StringBuffer:

The String class implements immutable character strings, which are read-only once the string has been created and initialized. Whereas the StringBuffer class implements dynamic character strings. Strings are immutable (can’t be changed), so manipulating strings often causes many temporary string objects to be created, which can be quite inefficient. StringBuffer are better choices in these cases. Their toString() method can be used to get a String value. It isn’t necessary to create them with a specific size, it will expand as necessary.

 

 

3. StringBuilder class

StringBuilder is basically identical to the older StringBuffer, but is slightly faster because it isn’t synchronized. The StringBuilder methods are same as the methods of the StringBuffer.