Tutorial Java SCJP – #12 Immutable, String and Integer

3 comments - This post in romanian

Immutable objects are objects that don’t change their value once they are created. The most known immutable object in Java is String. Besides String, there is another immutable object, and this is Integer (the class and not the primitive) which has an interesting behavior for values between -128 and 127 .

Other topics that are part of this Java tutorial are accessible through Java 6 Tutorial – Contents.

Based on the definition of the immutable object, if you want to implement your own immutable class, it will look like this:

final class MyImmutable
{
    private final int value;	//define it final
    public MyImmutable(int Value)
    {
        value = Value;
    }
 
    public int getValue() {
        return value;
    }
}

The immutable class

  • is defined final to prevent inheritance;
  • the attribute is defined final to block changing its value;
  • doesn’t contain methods that allow changes of the attribute value;

We have seen in Tutorial Java SCJP – #10 How to use String, StringBuilder and StringBuffer that String objects:

  • are immutable;
  • their values are stored in String constant pool when using = operator to initialize the object value;
  • when = is used, the JVM creates a new String object in String constant pool if that value hasn’t been used before; otherwise the reference gets the String object address.

Another type of immutable object in Java, is Integer (there are others, like Double, Color, …). Beside that, there is another interesting fact about Integer.

Integer values ranging from -128 to 127 are stored by the JVM in an area similar to String constant pool because they are used in many situations.

The next example will prove this fact:

        Integer i1 =100;            //use constant values
        Integer i2 =100;            //use small values
 
        if(i1 == i2)        //compare the references
            System.out.println("references are EQUAL !");
        else
            System.out.println("references are NOT equal !");
 
        i1 = 300;          //use bigger values
        i2 = 300;
 
        if(i1 == i2)
            System.out.println( "references are EQUAL !");
        else
            System.out.println("references are NOT equal !");

The source code prints:

references are EQUAL !
references are NOT equal !

In the first sequence of initializations, in which there are used values between -128 and 127, the 2 Integer references are equal because they reference the same Integer object.

When the values are outside -128 and 127 interval, the 2 references are different because we have 2 different Integer objects with the same value.

Other topics that are part of this Java tutorial are accessible through Java 6 Tutorial – Contents.

,