This is very popular interview question in core java interview. Most of us will answer it, String is immutable. When the question is goes why String is immutable, few of us only answer it, due to misunderstanding of immutable.
Here we will discuss about why?.
Immutable is, once a string object created in string pool or heap we cannot change the value of it. But we can change the value of the reference. That's what we are doing in below code.
String name = "Boomi";
name = "raj";
But we are able to change it right??. Its not what immutable means. Immutable means we cannot edit the "Boomi" from string pool. Let see how above string stored in java memory.
When we create name = "Boomi"; value "Boomi" will be create in string pool and assigned this value to name reference.
Now you may have a question why java engineers made string as immutable.
Let see an example to understand why string immutable?
String name = "Boomi";
String userName = "Boomi";
Here we are creating two string with same name. If String is mutable then we need to create two time value "Boomi". So it might consume lot of memory for real time application.
Another reason for String immutability is security.
Let change name value to "Boomiraj".
name = "Boomiraj";
New Object will be created for "Boomiraj" this referred to name variable. userName still referring to the "Boomi".
We know we can create String object two ways,
- by using "". eg String name = "Boomi"; //Object stored in string pool
- by using new. eg String userName = new String("Boomi");//Object stored in heap memory.
String name = "Boomi";
String userName = "Boomiraj";
String nameObj = new String("Boomi");
String userNameObj = new String("Boomiraj");
System.out.println(name == nameObj); //false
System.out.println(userName == userNameObj);//false
No comments:
Post a Comment