Saturday 16 March 2013

Interview Question #4 What is immutable object? Can you write immutable object?

Immutable classes in java are classes whose object cannot be modified. Most instance variables and functions of immutable classes are also final in order from preventing subclasses to change the values by overriding methods which may compromise immutability. But there are other ways too, like declaring the members as private and changing it's value only in constructor.

For more details on how you can make your class immutable refer -

There can be more follow up questions like why would you make a class immutable? Well the answer is thread safety :) as immutable objects are inherently thread safe. More details in the linked answer above.

      For example in Java String is an immutable class. Once a string is created it cannot be modified.What happens when we call functions like .substring() one might ask. What it does is it simply creates and returns a new String object by taking the sub-string from the source string.

    Other example includes the wrapper classes for the primitive types: java.lang.Integer, java.lang.Byte, java.lang.Character, java.lang.Short, java.lang.Boolean, java.lang.Long, java.lang.Double, java.lang.Float etc.

Yo know why String was decided to be made immutable go through the following article -


Related Links

No comments:

Post a Comment

t> UA-39527780-1 back to top