Is the "new String ()" immutable?

I have been studying Java String for a while. The following questions are based on the following posts.

Java String is special
String immutability in java

  • Invariance: Now, following immutability, the String class has been designed so that values โ€‹โ€‹in the shared pool can be reused in other places / variables. It is good if String was created as

    String a = "Hello World!"; However, if I create a String as

    String b = new String("Hello World!"); why is it immutable? (or that?). Since it has allocated heap memory, I should be able to modify this without affecting any other variable. So, by design, was there any other reason why String is generally considered immutable? Or is my assumption wrong?

  • Secondly, I wanted to ask about a common row pool. If I create a string object as

    String c = ""; - an empty entry created in the pool?

Are there any other posts? If so, can anyone share the link?

+73
java string immutability
Jan 27 '14 at 8:02
source share
15 answers

new String() is an expression that creates String ... and a String unchanged, regardless of how it is created.

(the question of whether new String() volatile or not is pointless. This is program code, not value. But I suppose this is not what you really meant.)




If I create a string object since String c = ""; - an empty entry created in the pool?

Yes; those. an entry is created for an empty line. There is nothing special about an empty String .

(To be pedantic, the pool entry for "" is created long before your code is executed. In fact, it is created when your code is loaded ... or perhaps even earlier than that.)




So, I wanted to know if the new heap object is immutable ...

Yes it is. But immutability is a fundamental property of String objects. All String objects.

You see that the String API simply does not provide any methods for modifying a String . Therefore (except for some dangerous and silly 1 tricks using reflection) you cannot mutate String .

and if so, what was the purpose ?.

The reason Java String designed as an immutable class is simplicity. This makes it easier to write the right programs and read / explain other people's code if the main class of strings provides an immutable interface. (Or, at least, this is the rationale for this design decision, as I understand it).

Following the answer, I understand that other references to the same variable are one of the reasons. Please let me know if I understand this correctly.

No. This is more fundamental than that. It's just that all String objects are immutable. Understanding this does not require complicated special argumentation. It just โ†’ is <lt ;.

For the record, if you want to use a mutable "string" object in Java, you can use StringBuilder or StringBuffer . But these are different types for String.




1 - The reason these IMO tricks are dangerous and stupid is because they affect the values โ€‹โ€‹of strings that are potentially shared by other parts of your application through the string pool. This can lead to chaos ... because the next guy supporting your code has little chance of tracking.

+105
Jan 27 '14 at 8:06
source share

A string is immutable no matter how it is created

1) The short answer is yes, new String() also immutable.

Since any possible mutable operation (for example, replace , toLowerCase etcetra) that you perform on a String does not affect the original String instance and returns you a new instance.

You can check this in Javadoc for String . Each public String method that is exposed returns a new instance of String and does not change the current instance to which you called the method.

This is very useful in a multi-threaded environment, since you do not need to think about volatility (someone will change the value) every time you pass or exchange a String . String may be the most popular data type, so designers have blessed us all not to think about volatility every time and saved us a lot of pain.

Immutable Permitted String Pooling or Caching

It was because of the immutability property that the internal string pool was possible, because when the String value is required elsewhere, this immutable link is returned. If String would be modified then it would be impossible to split String like this to save memory.

String unmatched was not pool related, but immutability has more advantages associated with it.

Interpreting or concatenating strings is an example of a Flyweight design pattern.

2) Yes, it will be interned like any other String , since an empty String also the same String as other String instances.

Literature:

+42
Jan 27 '14 at 8:06
source share

Java libraries are highly optimized around the limitation that any String object is immutable, no matter how this object is created. Even if you create b with new , the other code that you pass to this instance will treat the value as immutable. This is an example of the Value Object template, and all the benefits (thread safety, no need to make private copies) apply.

An empty string "" is a legitimate String object, like everything else, there is simply no internal content, and since all constant compile-time strings are interned, I actually guarantee that some runtime library has already called it to the pool.

+18
Jan 27 '14 at 8:06
source share

1) The immutable part is not due to the pool; it just makes the pool possible in the first place. Strings are often passed as arguments to other functions or even in conjunction with other threads; Creating immutable strings was a constructive solution to facilitate discussion in such situations. So yes - String in Java is always immutable, no matter how you create them (note that in java it is possible to have mutable strings in java - just not with the String class).

2) Yes. Probably. I'm actually not 100% sure, but that should be so.

+14
Jan 27 '14 at 8:07
source share

From Oracle Java Documentation :

Lines are constant; their values โ€‹โ€‹cannot be changed after they are created .

And again:

String buffers support mutable strings. Because String objects are immutable, they can be shared.

Generally speaking: "all primitive" (or related) objects are immutable (please accept my lack of formalism).

Associated Stack Overflow entry:

  • String immutability in Java
  • Is a Java string immutable?
  • Is Java "pass-by-reference" or "pass-by-value",
  • Is the Java string really immutable?
  • The string is unchanged. What exactly does it mean?
  • why do we need a string that is immutable in java?

About the object pool: The object pool is a java optimization that is NOT immutable.

+7
Jan 27 '14 at 8:13
source share

This is not strictly the answer to your question, but if behind your question there is a desire for mutable strings that you can manipulate, you should check out the StringBuilder class, which implements many of the same methods that String contains, but also adds methods for changing current content.

Once you have constructed your string in such a way that you are content with it, you simply call toString() on it to convert it to a regular String , which you can pass to library programs and other functions that accept only String s.

In addition, both StringBuilder and String implement the CharSequence interface, so if you want to write functions to your own code that can use both mutable and immutable strings, you can declare them to accept any CharSequence object.

+7
Jan 27 '14 at 8:14
source share

The line is immutable, meaning that you cannot change the object itself no matter how you created it. And as for the second question: yes, he will create a record.

+6
Jan 27 '14 at 8:07
source share

This is actually the opposite.

[...] the String class was designed so that the values โ€‹โ€‹in the shared pool could be reused in other places / variables.

No, the String class is immutable, so you can safely refer to its instance without worrying that it is being modified from another part of your program. That is why unification is possible in the first place.

So, consider the following:

 // this string literal is interned and referenced by 'a' String a = "Hello World!"; // creates a new instance by copying characters from 'a' String b = new String(a); 

Now, what happens if you simply create a link to the newly created variable b ?

 // 'c' now points to the same instance as 'b' String c = b; 

Imagine that you pass c (or, more specifically, the object it refers to) to a method in another thread and continue to work with the same instance in your main thread. Now imagine what happens if the lines are mutable.

Why is this so?

If nothing else, this is because immutable objects make multithreading much easier and usually faster. If you pass a mutable object (which will be any object with a state, with mutable private / public fields or properties) between different streams, you need to be especially careful to ensure synchronized access (mutexes, semaphores). Even so, you need special care to ensure atomicity in all your operations. Multithreading is tough.

Regarding performance implications, note that quite often copying an entire line to a new instance to change even a single character is actually faster than causing an expensive context switch due to the synchronization constructs needed to provide thread-safe access, And, as you mentioned, immutability also offers interning options, which means it can help reduce memory usage.

It is usually a pretty good idea to do as much as you can .

+5
Jan 27 '14 at 9:56 on
source share

1) Immutable: A string will be immutable if you create it using a new or different method for security reasons.

2) Yes, there will be an empty entry in the row pool.

You can better understand the concept using code

  String s1 = new String("Test"); String s2 = new String("Test"); String s3 = "Test"; String s4 = "Test"; System.out.println(s1==s2);//false System.out.println(s1==s3);//false System.out.println(s2==s3);//false System.out.println(s4==s3);//true 

Hope this helps your request. You can always check the source code for the String class in case of a better understanding. Link: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java

+4
Jan 27 '14 at 8:38
source share

1- The string is unchanged . See the following:

Is the Java string really immutable?

This way you can create it in many ways.

2-Short answer: Let it be empty.

+2
Jan 27 '14 at 9:53 on
source share

Created lines will always be immutable no matter how they are created.

Answers to your questions:

  • The only difference:
    When a string is created as - {String a = "Hello World!";} Then only one object is created .
    And when it is created as - {String b = new String("Hello World!");} Then two objects are created. The first is because you used the keyword 'new' , and the second is the String property.

  • Yes of course. An empty entry will be created in the pool.

+2
Jan 27 '14 at 10:23
source share

The line is immutable because it does not give you the opportunity to change it. This is a design to avoid any fakes (it is final, the main array should not be affected ...).

Similarly, Integer is immutable because there is no way to modify it.

It doesn't matter how you create it.

+1
Jan 27 '14 at 19:38
source share

Invariance is not a feature of new ; it is a feature of the String class. It does not have mutator methods, so it is immutable.

+1
Jan 27 '14 at 20:05
source share
  String A = "Test" String B = "Test" 

Now String B called "Test" .toUpperCase () which change the same object into "TEST" , so A will also be "TEST" `, which is undesirable.

+1
Feb 28 '14 at 7:17
source share

Please note that in your example, the link changes, not the object to which it refers, i.e. b as a reference, may be modified and refer to a new entity. But this new object is immutable, which means that its contents will not be changed "after" the constructor call.

You can change the line with b=b+"x"; or b=new String(b); , and the contents of the variable a seem to change, but do not confuse the immutability of the link (here the variable b ), and the object is referencing (think of pointers in C). The object referenced by the link will remain unchanged after it is created.

If you need to change the string by changing the contents of the object (instead of changing the link), you can use StringBuffer , which is a mutable version of String.

0
Mar 10 '15 at 13:58
source share



All Articles