Are Strings *really* immutable in Java? - java

Everyone knows that Java's String object is immutable which essentially means that if you take String object a and concatenate it with another String object, say b, a totally new String object is created instead of an inplace concatenation.
However, recently I have read this question on SO which tells that the concatenation operator + is replaced with StringBuilder instances by the compiler.
At this point, I get a bit confused since, as far as I know and think, the StringBuilder objects are mutable due to their internal structure. In this case, wouldn't this essentially make String objects in Java mutable ?

Not really.
The actual Strings are still immutable, but in compile time, the JVM can detect some situations where the creation of additional String objects can be replaced by a StringBuilder.
So if you declare a String a and concatenate with another String, your a object doesn't change, (since it's immutable), but the JVM optimizes this by replacing the concatenation with the instantiation of a StringBuilder, appending both Strings to the Builder, and finally assigning the resulting String.
Let's say you have:
String a = "banana";
String d = a + "123" + "xpto";
Before the JVM optimized this, you would essentially be creating a relatively large number of Strings for something so simple, namely:
String a
String "123"
String "xpto"
String a + "123"
String a+"123"+"xpto"
With the optimization of transforming concatenation into a StringBuilder, the JVM no longer needs to create the intermediate results of the concatenation, so only the individual Strings and the resulting one are needed.
This is done basically for performance reasons, but keep in mind that in certain situations, you'll pay a huge penalty for this if you aren't careful. For instance:
String a = "";
for(String str: listOfStrings){
a += str;
}
If you were doing something like this, in each iteration the JVM will be instantiating a new StringBuilder, and this will be extremely costly if listOfStrings has a lot of elements. In this case, you should use a StringBuilder explicitly and do appends inside the loop instead of concatenating.

Strings are immutable objects. Once you concatenate it with another String, it becomes a new object. So remember - you don't change the existing String, you just create a new one.

Strings really are immutable. The compiler may generate code involving StringBuilder, but that is just an optimization which does not change how the code behaves (apart from performance). If there was some case where you could observe mutation (e.g. by keeping a reference to one of the intermediate results), the compiler would have to optimize in a way that still gives you an immutable string for that intermediate reference.
So if StringBuilder is used under the covers, even if you can't directly see the difference, doesn't that still mean that mutability is involved? Well, yes, but if you get down to it all the RAM in your PC is mutable. The memory of immutable objects can be moved around by the garbage collector, which definitely involves mutation as well. In the end, the important thing to you as a programmer is that this mutation is hidden from you, and you get a big promise that your program will behave the way you expect, i.e. you'll never see mutation in an immutable object (except in cases of severe problems, e.g. faulty RAM).

Related

What's the difference between StringBuilder and ArrayList<String>?

In an interview, I want to build up a new String with some substrings. I argued that ArrayList<String> is almost the same as StringBuilder, but the interviewer said I should always use StringBuilder if I need to deal with String. I think the time complexity of adding/removing functions between them are the same.
They aren't the same thing at all. StringBuilder builds a single string, while ArrayList<String> is just that--an array of separate strings. Of course, you can concatenate all of the array's strings with String.join("", list), where the first argument is the separator that you want to use, but why would you go that route instead of just using the class that was designed to do exactly what you're trying to do in the first place?
It all comes down to memory consumption. String is an object, while ArrayList<String> holds separate objects, StringBuilder holds only one.
StringBuilder has a member function to return the whole built string, whereas in ArrayList, you have to concatenate the strings yourself.
Unless you continue to need the separate elements you are adding to the list, you should use a StringBuilder.
After all, you can't directly get a concatenated string from the contents of the list: you have to put it in, say, a StringBuilder.
But in the specific case of building up a string of substrings, StringBuilder provides methods to allow you to append portions of Strings without using substring: the append(CharSequence, int, int) method is an optimization to avoid creating that extra string.
It should be mentioned that, at least when I have written python, it has been considered better to build up a list, and then use ''.join(theList) at the end, which is basically the analog of ArrayList<String>.
I don't know enough about python to know why this is considered particularly better.
You can "build" strings using both. However StringBuilder is a class specializing in building strings with its append insert delete charAt etc... methods. An ArrayList is a general purpose collection which lacks most of this functionality. Consider implementing the following (contrived example) with an ArrayList:
StringBuilder sb = new StringBuilder().append("time: ")
.append(System.currentTimeMillis())
.deleteCharAt(4)
.reverse();
System.err.println(sb); // 3153067310451 emit
Ergonomics and readability aside, there are performance considerations but those are largely irrelevant on trivially sized examples.
If you need a single String at the end, performance and memory consumption are some differences for sure. Whenever you build a String from parts, in the good case you end up using StringBuilder, or in a slightly worse case StringBuffer, and in the worst case you end up concatenating two strings, then throw them away, and repeat - lots of allocations and garbage collection in this case.
JLS12 still mentions StringBuffer by name for optimization (but hopefully StringBuilder is used internally, as similar technique):
An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.
In the particular case of having a List<String> and later using String.join() on it, StringJoiner contains the particular StringBuilder object which is going to be used.
So there will be a builder anyway, and then it may be more efficient to use it from the beginning.

Why do I need to redefine a String if I use the method replace?

Why do I need to redefine the variable theString if I use the method replace in this code :
String theString = "I w#nt to h#ve the regul#r \"A\"!";
theString = theString.replace("#", "a");
System.out.println(theString);
Why can't I do :
theString.replace("#", "a");
and that's it?
Strings are immutable -- you cannot change them once they have been created. There are exceptions of course, if you use reflective magic, but for the most part, they should be treated as invariants. So therefore the method replace(...) does not change the String, it can't, but rather it creates and returns a new String. So to be able to use that new String, you have to get access to its reference, and that can be done by assigning it to a String variable or even to the original String variable. This discussion gets to the heart of what is the difference between an object and a reference variable.
Because String objects are, by design, immutable, so you need to create a new String to contain your changes
The posted answers mention the technical reason (strings are immutable) but neglect to mention why it is that way. See this: Why are strings immutable in many programming languages?
Taken from this link
In Java, String is not implemented as character arrays as in other programming languages. Instead string is implemented as instance of String class.
Strings are constants/ immutable and their values cannot be changed after they are created. If any operations that results in the string being altered are performed a new instance of String object is created and returned. This approach is done for implementation efficiency by Java.
It is recommended to use StringBuffer or StringBuilder when many changes need to be performed on the String. StringBuffer is like a String but can be modified. StringBuffer is thread safe and all the methods are synchronized. StringBuilder is equivalent to StringBuffer and is for use by single thread. Since the methods are not synchronized it is faster.

About the String#substring() method

If we take a look at the String#substring method implementation :
new String(offset + beginIndex, endIndex - beginIndex, value);
We see that a new String is created with the same original content (parameter char [] value).
So the workaround is to use new String(toto.substring(...)) to drop the reference to the original char[] value and make it eligible for GC (if no more references exist).
I would like to know if there is a special reason that explain this implementation. Why the method doesn't create herself the new shorter String and why she keeps the full original value instead?
The other related question is : should we always use new String(...) when dealing with substring?
I would like to know if there is a special reason that explain this implementation. Why the method doesn't create herself the new shorter String and why she keeps the full original value instead?
Because in most use-cases it is faster for substring() to work this way. At least, that's what Sun / Oracle's empirical measurements would have shown. By doing this, the implementation avoids allocating a backing array and copying characters to the array.
This is only a non-optimization if you have to then copy the String to avoid a memory leakage problem. In the vast majority of cases, the substrings become garbage in a relatively short period of time, and there is no long-term leakage of memory.
Hypothetically, the Java designers could have provided two versions of substring, one which behaved as currently, and the other that created a String with its own backing array. But that would encourage the developer to waste brain-cycles thinking about which version to use. And then there's the problem of utility methods that build on substrings ... like the Pattern / Matcher classes for instance. So I think it is a good thing that they didn't.
Because String is immutable class
Also See
http://javarevisited.blogspot.it/2010/10/why-string-is-immutable-in-java.html (Courtesy: Luca Geretti )
The reason for this implementation is efficiency. By pointing to the same char[] as the original string, no data needs to be copied.
This does have a downside though, as you've already hinted at yourself. If the original string is long and you just want to get a small part of it, and you don't need the original string anymore after that, then the complete original array is still referenced and can't be garbage collected. You already know how to avoid that - do new String(original.substring(...)).
should we always use new String(...) when dealing with substring?
No, not always. Only when you know it might cause problem. In many cases, referring to the original char[] instead of copying the data is more efficient.

No reverse method in String class in Java?

Why there is no reverse method in String class in Java? Instead, the reverse() method is provided in StringBuilder? Is there a reason for this? But String has split(), regionMatches(), etc., which are more complex than the reverse() method.
When they added these methods, why not add reverse()?
Since you have it in StringBuilder, there's no need for it in String, right? :-)
Seriously, when designing an API there's lots of things you could include. The interfaces are however intentionally kept small for simplicity and clarity. Google on "API design" and you'll find tons of pages agreeing on this.
Here's how you do it if you actually need it:
str = new StringBuilder(str).reverse().toString();
Theoretically, String could offer it and just return the correct result as a new String. It's just a design choice, when you get down to it, on the part of the Java base libraries.
If you want an historical reason, String are immutable in Java, that is you cannot change a given String if not creating another String.
While this is not bad "per se", initial versions of Java missed classes like StringBuilder. Instead, String itself contained (and still contains) a lot of methods to "alter" the String but since String is immutable, each of these methods actually creates and return a NEW String object.
This caused simple expressions like :
String s = "a" + anotherString.substr(10,5).trim().toLowerCase();
To actually create in ram something like 5 strings, 4 of which are absolutely useless, with obvious performance problems (despite after there has been some optimizations regarding underlying char[] arrays).
To solve this, Sun introduced StringBuilder and other classes that ARE NOT immutable. These classes freely modify a single char[] array, so that calling methods does not need to produce many intermediate String instances.
They added "reverse" quite lately, so they added it to StringBuilder instead of String, cause that's now the preferred way to manipulate strings.
As a side-note, in Scala you use the same java.lang.String class and you do get a reverse method (along with all kinds of other handy stuff). The way it does it is with implicit conversions, so that your String gets automatically converted into a class that does have a reverse method. It's really quite clever, and removes the need to bloat the base class with hundred of methods.
String is immutable, meaning it can't be changed.
When you reverse a String, what's happening is that each letter is switched on it's own, means it will always create the new object each times.
Let us see with example:
This means that for instance Hello becomes as below
elloH lloeH loleH olleH
and you end up with 4 new String objects on the heap.
So think if you have thousands latter of string or more then how much object will be created.... it will be really a very expensive. So too much memory will be occupied.
So because of this String class not having reverse() method.
Well I think it could be because it is an immutable class so if we had a reverse method it would actually create a new object.
reverse() acts on this, modifying the current object, and String objects are immutable - they can't be modified.
It's peculiarly efficient to do reverse() in situ - the size is known to be the same, so no allocation is necessary, there are half as many loop iterations as there would be in a copy, and, for large strings, memory locality is optimal. From looking at the code, one can see that a lot of care was taken to make it fast. I suspect the author(s) had a particular use case in mind that demanded high performance.

Why isn't String() constructor private?

Is using a String() constructor as against string literal beneficial in any scenario?
Using string literals enable reuse of existing objects, so why do we need the public constructor? Is there any real world use?
For eg., both the literals point to the same object.
String name1 = "name";//new String("name") creates a new object.
String name2 = "name";
One example where the constructor has a useful purpose: Strings created by String.substring() share the underlying char[] of the String they're created by. So if you have a String of length 10.000.000 (taking up 20MB of memory) and take its first 5 characters as substring then discard the original String, that substring will still keep the 20MB object from being eligible for garbage collection. Using the String constructor on it will avoid that, as it makes a copy of only the part of the underlying char array that's actually used by the String instance.
Of course, if you create and use a lot of substrings of the same String, especially if they overlap, then you'd very much want them to share the underlying char[], and using the constructor would be counterproductive.
Since string is immutable, operations like substring keep the original string that might be long. Using the constructor to create new string from the substring will create a new string and will allow dropping the old string (to GC). This way might free up needed memory.
Example:
String longS = "very long";
String shortS = new String(longS.substring(4));
Because sometimes you might want to create a copy and not just have a new reference to the same string.
All good answers here, but I think it's worth pointing out that the Java treats literals quite different than Strings constructed the traditional way.
This is a good Q/A about it.

Categories