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.

public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
/** Cache the hash code for the string */
private int hash; // Default to 0
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;
...
}
view raw String.java hosted with ❤ by GitHub

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,

public class ImmutableString{
public static void main(String args[]) {
String immutable = "javaonjava";
System.out.println("First String " + immutable);
immutable = "stringchanged";
System.out.println("Changed String " + immutable);
}
}


First String javaonjava
Changed String stringchanged

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


public class StringEquality{
public static void main(String args[]) {
String first = "javaonjava";
String second = "javaonjava";
System.out.println("first equals second "+ (first == second));
}
}


first equals second true
view raw result.cmd hosted with ❤ by GitHub


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

2. No operations modify String

public class ImmutableString{
public static void main(String args[]) {
String immutable = "javaonjava";
immutable.substring(2,5);
System.out.println(immutable);
immutable.concat("somemore");
System.out.println(immutable);
}
}


javaonjava
javaonjava
view raw result.cmd hosted with ❤ by GitHub


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

public class ImmutableString{
public static void main(String args[]) {
String immutable = "javaonjava";
immutable = immutable.substring(2,5);
System.out.println(immutable);
immutable = immutable.concat("somemore");
System.out.println(immutable);
}
}
view raw Immutable.java hosted with ❤ by GitHub


vao
vaosomemore
view raw result.bat hosted with ❤ by GitHub


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