I know Strings are immutable in nature. But I have a question.
String a = new String("abc");
If we create a string like above instead of a literal, then isn't it not immutable any more since it is created as a new object? Please clarify. Thanks.
I know Strings are immutable in nature. But I have a question.
String a = new String("abc");
If we create a string like above instead of a literal, then isn't it not immutable any more since it is created as a new object? Please clarify. Thanks.
No. It doesn't. A java String is always immutable irrespective of how it is created.
Actually using new
to create Strings is redundant and should be avoided in 99 percent of the cases (unless you are doing some micro-bench marking)
Immutable means an instance cannot be modified once it is created. When you look at all the methods of String, none of them actually modifies the original String passed to it. They either return the same String or create a new one.
Your String
is immutable as String is always immutable (view The Java Language Specification)
The difference between String a = "abc";
and String a = new String("abc");
is not the mutability, is the use of the String pool. When you do
String a = "abc";
you are using the Java String pool (See String intern)
And when you do
String a = new String("abc");
you are not using the String pool.
The String pool stores different String instances, that's why when you create two different objects using the pool, the references are the same.
In both cases anyways, you cannot change the state of your String instance (String
is immutable).
Creating Strings using new
can be avoided almost always.
This is a mutable object:
class Person {
private name;
Person(String name) { this.name = name; }
void setName(String name) { this.name = name; }
}
Because you can change its state after it has been created:
Person john = new Person("John");
john.setName("Fred"); //oops, John's name is not John any more...
On the other hand, once you have created a String there is no method that allows you to change the value of that string.
String john = "John";
john.setValue("Fred"); //No, that's not possible...
That does not prevent you from creating new Strings with similar or different values of course.