Home - SafiaSafia/learning-java-4 GitHub Wiki

Q NO 1= what is mutable an immutable objects in java? ANS= An mutable object is a kind of object whose state cannot be modified after it is created. this is as opposed to a mutable object, which can be modified after it is created. in java, objects are referred by reference.if object is known to be immutable the abject reference can be shared. for example Boolean ,Byte, Character,Double, Flout, Integer, String,Long Short, are immutable class in java, but the class buffer is a mutable object in addition to be immutable strings. class program { public static void main(string arg[]){ String str="hi"; System.out.println(str); str.tolower(); System.out.println(str); } } // output is// HI HI From the above example, the toLower() method does not impact on the original content in str. What happens is that a new String object "hello" is constructed. The toLower() method returns the new constructed String object's reference. Let's modify the above code: Class program { public static void main(string arg[]){ String str="HI"; System.out.println(str); String str1=str.toLower(); System.out.println(str1); } } // the output is // HI hi The str1 references a new String object that contains "hello". The String object's method never affects the data the String object contains, excluding the constructor.

In Effective Java, Joshua Bloch makes this recommendation: "Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, you should still limit its mutability as much as possible.