When we talk with example once we create a String object and providing value we cannot change the value of the string object. That why we can call String object as a non mutable. Whereas String buffer object we can change its value.
Lets we discuss more about String class. We can create a String Object in two ways. First one declaring a variable and initializing this variable with value. So let’s we can take “Hello”
String s1=”Hello”;
Second way to create a String Object creating instance of a class.
String s1=new String(“Hello”);
The above 2 ways are creating a String Objects in Java. Let’s we assume we want to create other String Object using both of above two ways.
Example:
Method 1: String s2=”Hello”;
Method 2: String s2=new String(“Hello”);
The Method 1 String s2 particular string memory allocation will be done in memory allocation would be done in free poll of memory, that is in the method area. Whereas in case of Method 2 since we are declaring as new String() the memory allocation of the String is made on the Heap area.
When we create a other String object Using the method 1 and that String too have a same value ( example : String s4=”Hello”;) Then it will bother to create another memory space for this s4 Object. Rather s2 and S4 pointing to the same memory location. So in that case when we compare two String to see whether both the String are equal.
Example 2:
if(s2==s4)
The above example will return true because in this Example 2 we are comparing the address not the content. In this case both will point to same memory location. So it will return true.
Where as in the Method 2 i am creating the same String i will get two different memory location for both objects. For s2 one memory allocation and for s4 another memory allocation. In this case if we take example 2 to compare this it will return false. Because method 2 referring two different addresses.
Example 3:
String s=”EshuSoft”;
s+=”Java”;
As we know String is non-mutable object we cannot change the value. In this Example 3 When we try to change the value of the object internally JVM what it does is it create a StringBuffer Object to append the value.
StringBuffer Class contains the methods like insert(), replace(), append(), etc.
So in this Example 3 StringBuffer object created internally and append the Java. So it will be like s=new StringBuffer(“EshuSoft+”).append(“Java”).
So finally we will get EshuSoftJava.
String is immutable means once the string object is created we can’t change the value. It means when you add value into the same string object it will take a help of string buffer to append both value.