Friday, November 21, 2014

Need for Immutable String in Java

While understanding String Immutability there were some answered questions as to why the designers of Java made String Immutable. We checked that String is immutable but Why so?

Well, it's difficult to go inside the brain of designers of java but based on the usage as of today we can speculate as to what would have been going on in their brain while making java immutable.

1. Easy storage and housekeeping
Strings are used a lot inside a program. A lot of Strings are repeated. For example in a College Database application, same names (Strings) are repeated again and again. Hence it makes better sense to keep a single copy of all strings at a single place (String Pool). Instead of creating new objects again and again. Garbage Collection and Storage of these high volume data becomes easy.



2. Hashcode does not change
Since Strings are immutable, their hascode won't change like other objects. Thus Strings do not calculate hashcode every time we call hashcode function, Hascode us kept cached. Since Strings are used a keys in HashMaps and other such Structures, we save a lot of time but not calculating hashcode every time we need to retrieve an Object.

3. Network Security
All passwords we enter online are strings. Bank details are passed as Strings. If they are mutable, anyone could change them over the network, which would wreak havoc. Same goes with classnames while loading a Class. 

4. Prevents Concurrency Issues
Since Strings are immutable, hence no need to synchronize. Hence no concurrency issues while using Strings.

Friday, November 14, 2014

String immutable in Java: What does it really mean?

This is one of the favourite questions at the fresher level that interviewer asks. Most of the candidates tend to gloss over this. If interviewer tends to go into this deep, most of the candidates tend to falter. At least that if what I have observed having interviewed hundreds of candidates in the past.

We will try and make this article single point of reference for Strings in Java. Hopefully we cover something that might be helpful to you. Read here, for knowing Why It was made Immutable.

Let's try and go in depth on String immutability.

Let's start by Source Code of String.java. I always say that source code is the best resource to learn a language.


How String is Immutable?
This question is self answered by the above code snippet. Member variable data type is final. Hence String Object once created becomes immutable in Java.

How come then we are able to assign same variable, a different value?
Now we are talking. Valid question. Let's check it via code,




So the question stands. What does immutability means?

Well, it can be explained by what happens internally. Variable immutable refers to a memory space which is allocated to "javaonjava. This memory allocation is what we call immutable. Same variable can point to different memory spaces.

String literals are stored separately in a String Pool. Once a String is Created, say "javaonjava". Whenever a new variable needs "javaonjava" String, a new String is not created. The old one is referenced. This is what we mean by immutability. So String Object is not immutable, String itself is immutable.

Compare it with any User defined object. When that object is updated, content is re-written on the same memory space. Hope things are getting clear now.

How to check String is immutable in Java

1. == (equals operator), is the best check.
As we read above StringPool contains single copy of a given String. So if this operator returns true on two string variables, it means they are pointing to same memory and content inside the StringPool






Thus we see, they both point to the same content.

2. No operations modify String





Thus we see neither concat, nor substring modifies the String. They simply create a new String, which is returned as we see below.





In the last example, what happens to "javaonjava" String. Well it remains in the StringPool but unreferenced. If not reused for considerable time, it could be Garbage Collected.

See the diagram below for better understanding