Yes, Strings are immutable in java. Lets elaborate this with the
help of some examples.
There are two ways to declare and define a String value in java
1. String s = new
String(“xyz”);
2. String s = “xyz”;
In both the ways a new String object is created and is assigned
with the value “xyz”. But in first way a single object is created in String
pool and values “xyz” is refer to it and in second way two object are created
as one in String pool and one in non string pool.
So far the string object is just behaving like a normal object but
when we try to assign another value to same object created earlier referring
some value like
String s = “xyz”;
s = s.concat(“abc”);
This will append the “abc” at the end of the “xyz” and assign it
to s variable.
So what is immutability is all about which means we can’t assign
another value to object.
In java the String objects are immutable and this immutability is
achieved as
The VM(Java Virtual Machine) create another object with the
value “xyzabc” and refer it the String variable s. The older value “xyz”
still reside in the pool with the lost reference to s.
That’s why when we concat the string but not assign to to variable
it will not added to String variable
s = “xyz”;
s.concat(“abc”);
System.out.println(s);
It will still show the value “xyz”. To understand this more
clearly please see the example below
Example
Code:
public
class demoString {
public static void main(String s[])
{
String st = new String
("JAVA");
st.concat(" is great"); //we
created the new value JAVA is great but does not assign this to st
variable
System.out.println("The result of
String : "+st);//this will only print JAVA
String st1 = new String
("JAVA");
st1 = st1.concat(" is
great");//we created the new value JAVA is great and assign this to st1
variable
System.out.println("The result of
String : "+st1);//this will print JAVA is great
}
}
Output
:-
The
result of String : JAVA
The result of String : JAVA is great
No comments:
Post a Comment