How will you write an immutable class?

Writing an immutable class is generally easy but there can be some tricky situations. Follow the following guidelines: A class is declared final (i.e. final classes cannot be extended). public final class MyImmutable { … } All its fields are final (final fields cannot be mutated once assigned). private final int[] myArray; //do not declare as -> private final int[] myArray = null; Do not provide any methods that can change the state of the immutable object in any way – not just setXXX methods, but any methods which can change the state. The “this” reference is not allowed to … Click here to continue…..

What are the benefits of immutable objects?

Immutable classes can greatly simplify programming by freely allowing you to cache and share the references to the immutable objects without having to defensively copy them or without having to worry about their values becoming stale or corrupted. Immutable classes are inherently thread-safe and you do not have to synchronize access to them to be used in a multi-threaded environment. So there is no chance of negative performance consequences. Eliminates the possibility of data becoming inaccessible when used as keys in HashMaps or as elements inSets. These types of errors are hard to debug and fix.

What is an immutable object?

Immutable objects whose state (i.e. the object’s data) does not change once it is instantiated (i.e. it becomes a read-only object after instantiation). Immutable classes are ideal for representing numbers (e.g. java.lang.Integer, java.lang.Float, java.lang.BigDecimal etc are immutable objects), enumerated types, colors (e.g. java.awt.Color is an immutable object), short lived objects like events, messages etc.

What is the main difference between a String and a StringBuffer class?

String StringBuffer / StringBuilder String is immutable: you can’t modify a string object but can replace it by creating a new instance. Creating a new instance is rather expensive. //Inefficient version using immutable String String output = “Some text” Int count = 100; for(int i =0; i<count; i++) { output += i; } return output; The above code would build 99 new String objects, of which 98 would be thrown away immediately. Creating new objects is not efficient. StringBuffer is mutable: use StringBuffer or StringBuilder when you want to modify the contents. StringBuilder was added in Java 5 and it … Click here to continue…..

What is an intern() method in the String class?

A pool of Strings is maintained by the String class. When the intern() method is invoked equals(…) method is invoked to determine if the String already exist in the pool. If it does then the String from the pool is returned. Otherwise, this String object is added to the pool and a reference to this object is returned. For any two Strings s1 & s2, s1.intern() == s2.intern() only if s1.equals(s2) is true.