Saturday, November 16, 2013

String class 01 - Strings and String immutability

What is the String class ?

You may heard about packages in Java like java.util , java.lang and so on. String class is belongs to java.lang package. You need not to import this package to your program, it is imported by default by the compiler. But if you are not familiar with importing packages it will be a mess for you. Look at the following example to see how to import a package. In this program I have imported java.util.Scanner package. This is used to get a user input to a program(This things will be discussed later).

import java.util.Scanner;

public class Apple{
 public static void main(String args[]){
  Scanner scn = new Scanner(;
  System.out.print("Please enter your name: ");
  String name = scn.nextLine();
  System.out.println("Your name is: " + name);

I think now it is cleared. Only you need to understand that String class doesn't require any import statements. I will drop down the things in String class as follows.

  • Strings are objects like other objects.
  • They can create instances and they can have constructors and methods.
  • String is final class, so they can't be extended and overridden. 
  • Strings are immutable objects(We talk about this thing later in this post).
  • They can be assigned to String variables.
  • They can be used as parameters in methods and constructors.

How to create String objects ?

Really there are two ways to create String objects. 

First way:         String s = "apple";

  • In this situation String object is 'apple'. 's' is the reference variable to refer 'apple'.
  • It means in this way it is created one object and one reference variable.
  • "apple" will be placed at the heap area(pool) and "s" refers it.
Second way:     String s = new String ("apple");

  • In this way it creates two objects. Because we have used new keyword.
  • But both are not placed at the pool. "apple" object will be placed at the pool while another object(new String) stay in the normal memory. 

String immutability

  • Immutability means cannot  be changed. It means once you create a String, its value cannot  be changed again and it cannot be alternated.
  • That is called "String immutability". 
  • But you need to understand that, its reference variable is not immutable. It can be changed(Example program 01).
This is very important. Look at these examples. I think it is better, try these programs in your machine and compile and run to see the outputs. Then only you can understand, what I'm talking about.

Example program 01

public class StringTest1 {
 public static void main(String args[]){
  String x = "Nokia";

When you try this you can see the output is "Lumia". So now you may think what happen to "Nokia" String. I can express this program as follow graphical representation.

  1. First I have create a String object "Nokia", its reference variable is x.
  2. Then I created another String object "Lumia" with same reference variable(x).
  3. When you run the program, you can see the output as "Lumia".
  4. You may think what happen to Nokia object.
  5. It is still there in String pool(In the heap) without reference. Because now x is connected with "Lumia" object.

Example program 02

public class StringTest2 {
 public static void main(String args[]){
  String x = "Nokia";
  String y = x;
  y = "Lumia";

  1. In this situating first I created String object "Nokia". Its reference variable is "x".
  2. Then I assign "x" variable to another variable called "y".
  3. Now you can see both of variables point to "Nokia" object.
  4. In next line I created another String object "Lumia" which is referenced by "y".
  5. "y" was pointed to "Nokia", but now that connection is over and "y" now points to "Lumia" object.
  6. In this program x will print Nokia and y will print Lumia.

Example program 03

public class StringTest3 {
 public static void main(String args[]){
  String x = "Nokia";
  x.concat(" Lumia");

  String y = x.concat(" Lumia");

  1. In this program I have used java concat() method. This method belongs to java.lang.String package. What this method does is, concatenate String to the end of the another defined String.
  2. According to the second picture I have created x.concat("Lumia") String object.
  3. But I did not define a reference variable. Also in this case it is allocated memory in the pool for x.concat("Lumia") object.
  4. Then I assigned a new reference variable called "y" to x.concat("Lumia") object.

What is String Literal Pool ? 

String literal pool is a section of heap in the memory. This is pool of Strings which is maintained by JVM(Java Virtual Machine) to store Strings. Once you create a String, JVM checks it already exists in the pool. If it exist, a reference to the instance in the pool returns. If it not exists a new String object will be created. 

Why Strings are immutable ?

I said before, Strings are immutable. It is very valuable factor when you think about above situation with String literal pool. That optimization can only be done with String's immutability. If there is no immutability, we cannot talk about String literal pool which helps to reduce memory allocation in the memory and to reduce depending time. 

Try following program to understand,

public class StringTest2 {
 public static void main(String args[]){
  String s1 = "aaa";
  String s2 = "aaa";
  String s3 = new String("bbb");
  String s4 = new String("bbb");

Advantages of immutability 

  • It helps to reduce memory usage(Allowing identical values to be combined together and referenced from various locations in your codes)
  • It simplifies multi-threaded programming(Once you initialized, the value cannot be changed)
  • Safe to work(There is no problem with alternatives)  
  • It simplifies the design and implementation(Re-usability of a String )

Disadvantages of immutability

  • Less efficient(It creates a heavy garbage collection)

In this program(example 01), you can see it has a reference variable for Nokia object at first time. But then reference variable changed to Lumia. Then there is a object without reference(Nokia).