Pages

Sunday 22 February 2015

JAVA QUESTIONS

What is Immutable Object? Can you write Immutable Class?

Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example String is immutable in Java. Mostly Immutable classes are also final in Java, in order to prevent sub classes from overriding methods, which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor. Apart form obvious, you also need to make sure that, you should not expose internals of Immutable object, especially if it contains a mutable member. Similarly, when you accept value for mutable member from client e.g.java.util.Date, use clone() method keep separate copy for yourself, to prevent risk of malicious client modifying mutable reference after setting it. Same precaution needs to be taken while returning value for a mutable member, return another separate copy to client, never return original reference held by Immutable class

What is the difference between creating String as new() and literal?

When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap. For example, String str = new String("Test")does not put the object str in String pool , we need to call String.intern() method which is used to put them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool. By the way there is a catch here, Since we are passing arguments as "Test", which is a String literal, it will also create another object as "Test" on string pool.


No comments:

Post a Comment