Java supports different data types like int, char, float, double, boolean which are primitive data types. There are non-primitive data types like Array, String, Interface, Class, Enum. Though we say String as data type it’s actually a class in java.lang package. What makes String class so special? String is a collection of characters; characters include any type of character. Our main method in java takes in String array as arguments. All the text form of data needs String to store them.
Let’s start with how to create an object and store value in it. There are two ways to create string object,
![](https://static.wixstatic.com/media/f1f20f_33fe32e54f474570833cbaf973bf67f9~mv2.png/v1/fill/w_922,h_162,al_c,q_85,enc_auto/f1f20f_33fe32e54f474570833cbaf973bf67f9~mv2.png)
String object s1 is created using the new keyword, so it will be stored in heap memory like all java objects, but String s2 is created without new keyword, it is called string literal. S2 is stored in a special space in heap memory called as SCP or String Constant Pool.
We can confirm this by using a simple code. String class provides two operators namely “==” and “.equals”. They are different int the sense, “==” compares the object reference and .equals compares the value. In our case lets see what happens...
![](https://static.wixstatic.com/media/f1f20f_f4c8d080b93c4a508a53ad3c48b618fb~mv2.png/v1/fill/w_929,h_456,al_c,q_90,enc_auto/f1f20f_f4c8d080b93c4a508a53ad3c48b618fb~mv2.png)
The following screenshot explains that s1 and s2 both having the same value but referring different objects.
![](https://static.wixstatic.com/media/f1f20f_256296fe505e4a61a8bd25e78d724cd1~mv2.png/v1/fill/w_957,h_342,al_c,q_85,enc_auto/f1f20f_256296fe505e4a61a8bd25e78d724cd1~mv2.png)
Here we see the “== operator” compares the object references which shows two different objects have been created at different addresses that’s why we got false as the output.
Whereas the “.equals” operator compares the values that’s why we got the output as true.
Let’s see why String is called IMMUTABLE. String value cannot be changed. When we change the value of a String the old value is not overwritten, instead a new object is created and the field started pointing the new object. And the garbage collector plays it role by collecting the unused objects.
public static void main(String args[])
{
String s1= "String Manipulation";
String s2="String Manipulation";
System.out.println("I am address of s1: "+s1.hashCode());
System.out.println("I am address of s2: "+s2.hashCode());
s2="String Manipulation in Java";
System.out.println("After changing s2 value");
System.out.println("I am address of s1: "+s1.hashCode());
System.out.println("I am address of s2: "+s2.hashCode());
}
Output:
I am address of s1: 1577159500
I am address of s2: 1577159500
After changing s2 value
I am address of s1: 1577159500
I am address of s2: 1707510665
![](https://static.wixstatic.com/media/f1f20f_cf0c36fb44a2461493d897cad838c13f~mv2.png/v1/fill/w_888,h_424,al_c,q_90,enc_auto/f1f20f_cf0c36fb44a2461493d897cad838c13f~mv2.png)
Why String is immutable? Consider a scenario where a database is created for storing patient records. Patient1’city is Texas, Patient2 to Patient 50 has same city as Texas. So 50 objects are not created instead JVM looks for Texas which is already there so all the remaining patient city starts pointing towards Texas the single object. Now lets change the value of patient1’s city from Texas to NewJersey. What happens if String has been mutable. The value of Texas gets overwritten to NewJersey, all the remaining city’s reference will start pointing to null which results in null pointer exception
![](https://static.wixstatic.com/media/f1f20f_4bf0b97e28fc4be48c54aba23cb703ce~mv2.png/v1/fill/w_751,h_623,al_c,q_90,enc_auto/f1f20f_4bf0b97e28fc4be48c54aba23cb703ce~mv2.png)
But in reality since String is immutable, a new object for NewJersey gets created and the first patient city alone will points to the new object of NewJersey and the other city fields keep referring to the old object of Texas.
![](https://static.wixstatic.com/media/f1f20f_465029b5ed38445786f1928bece32eb8~mv2.png/v1/fill/w_763,h_639,al_c,q_90,enc_auto/f1f20f_465029b5ed38445786f1928bece32eb8~mv2.png)
Overriding toString()
To print an output in the console, we use “System.out.println()” function. When we call this function this calls the toString() method by default and converts everything into a String and prints in the console.
![](https://static.wixstatic.com/media/f1f20f_105e1d03dcf8407e8fbf7f4fc137eb2d~mv2.png/v1/fill/w_910,h_548,al_c,q_90,enc_auto/f1f20f_105e1d03dcf8407e8fbf7f4fc137eb2d~mv2.png)
In the above code snippet, we have tried to print a string object and java object. But why the outputs are different, if both the statements call toString() method. That’s because the toString() method is designed to print the hashcode of any object, but in String class this method is overridden to print the value of the input string. We can achieve this for the java object by manually overriding the toString() method as follows...
package stringManipulation;
public class ReadingObjectValue {
String string2;
public ReadingObjectValue(String string1) {
this.string2=string1;
}
public String toString() //overriden toString() method
{
return string2;
}
public static void ReadObjVal()
{
ReadingObjectValue obj=new ReadingObjectValue("Diyanika");
System.out.println(obj);
String s1=new String("Matuhra");
System.out.println(s1);
}
Output:
Diyanika
Matuhra
Functions in String
String class provide various functions to manipulate strings. Let’s discuss few of the functions with code snippets.
Searching Methods:
indexOf(), this method returns the index of a character or a string. This method has few variations.
String newstr="String Search methods";
System.out.println("index of char:" + newstr.indexOf('t'));
System.out.println("last index of char:" + newstr.lastIndexOf('t'));
System.out.println("index of string: "+ newstr.indexOf("ring"));
System.out.println("index of char after certain string: "+ newstr.indexOf("t",7));
For a given string the indexes start from 0. indexOf('t') method returns the first occurrence of alphabet ‘t’ in the string.lastIndexOf('t') displays the index of t in the string from the last. It reads the string in reverse. This indexOf("ring") is used to display the starting index of the string “ring”. IndexOf("t",7) displays the index of the occurrence of character 't', after the index 7. This is captured as output in the following screenshot.
OUTPUT:
![](https://static.wixstatic.com/media/f1f20f_747f731c05b84b0c9986096268d96bef~mv2.png/v1/fill/w_467,h_151,al_c,q_85,enc_auto/f1f20f_747f731c05b84b0c9986096268d96bef~mv2.png)
Character Extraction Methods:
charAt(), substring() are the two extraction methods in String. The charAt() function returns character and the substring() function returns a string.
str="Character Extraction in String";
System.out.println("charAt method: "+str.charAt(2)); //charAt
try {
System.out.println("o/p when we get indexvalue that is not present: "+str.charAt(200));//exception
System.out.println("o/p when we get indexvalue that is not present: "+str.charAt(-1));
} catch (Exception e) { e.printStackTrace(); }
System.out.println("substring sample:"+str.substring(0,10));//substring
CharAt(int index) function returns the character present at that index value. What if the index value we provide is larger than the length of the string itself or smaller than the string length. We get StringIndexOutOfBoundException in such cases. The substring(int startindex,int endindex) outputs the chararcter sequence present from start index to endindex excluding endindex gets displayed.
![](https://static.wixstatic.com/media/f1f20f_9086696fb71f4c608e5d30f007b235c5~mv2.png/v1/fill/w_980,h_549,al_c,q_90,usm_0.66_1.00_0.01,enc_auto/f1f20f_9086696fb71f4c608e5d30f007b235c5~mv2.png)
There are other widely used methods in String class. They are,
length() - returns length of a string
isBlank() - returns true when there are no characters
isEmpty() - returns true when string length is 0
trim() - trims blank spaces on both ends of a string
stripTrailing() - removes blank spaces in the end of a string
stripLeading() - removes blank spaces in the beginning of a string
replace(char,char) - this method replaces the first parameter charactes with the second parameter character
![](https://static.wixstatic.com/media/f1f20f_1db29e18580042e7b4b88cca8b8ced73~mv2.png/v1/fill/w_980,h_390,al_c,q_90,usm_0.66_1.00_0.01,enc_auto/f1f20f_1db29e18580042e7b4b88cca8b8ced73~mv2.png)
String Buffer and String Builder
String class is immutable for certain reasons, for security purpose, caching, synchronization. But sometimes this could be an inconvenience. Consider a scenario where we need to create paragraph from array of strings, if the paragraph has to have 500 words, then 500 objects will be created for each word. This is waste of memory and overload for Garbage Collector too. To avoid this we can use String builder or String buffer. Both are mutable. String buffer is thread safe, it provides synchronization because of that its slower than String builder which is not thread safe nut faster.
Below code snippet shows how single object is created in String buffer for each appended word in contrast to String where three separate objects are created.
![](https://static.wixstatic.com/media/f1f20f_4d5b8873391b4bce8d5c5ddc732f5a66~mv2.png/v1/fill/w_889,h_653,al_c,q_90,enc_auto/f1f20f_4d5b8873391b4bce8d5c5ddc732f5a66~mv2.png)
String is one of the vital class in Java. With its rich methods we could perform various operations. With string buffer and string builder classes we can achieve mutability as well.
Happy reading!!!