Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

what are the differences between final and immutable objects in java?

  Asked By: Jason    Date: Mar 22    Category: Java    Views: 13195

what are the differences between final and immutable
objects in java?



3 Answers Found

Answer #1    Answered By: Keith Marshall     Answered On: Mar 22

final  variable is one you cannot change once yu have
assigned a value to it. Ex.

final String str = "do not change me";

If you were to follow this with a line somewhere down
in your code that tries to reassign a new value to

Ex. str = "why not?";

you would get a compile time error.

An immutable object on the other hand means that you
there is no way for you to change the object. An
example of this is the String object. On initial
analysis it seems that it has methods that allow you
to change the object but this is not correct. For
example if you try.

String str = "hello world";
System.out.println(str.replaceAll("h", "q"));

You will see that the string held in str does not
change after all and that replaceAll returns a
modified string but does not modify the string itself.
The point is that there is no way to change the object
itself. Now you might be wondering what about if I did

str = str.replaceAll("h", "q");

you are not changing the object itself here but
makinging the variable point to another object (the
one returned by replaceAll. This is different from
changing the object itself.

Answer #2    Answered By: Thomas Camaroon     Answered On: Apr 18

Mutable and Immutable ?

In English Language Mutable means "can change" and immutable means "cannot change". The term Immutable Object means that the state of the Object cannot change after its creation. An immutable type sets the property or state of the object as read only because it cannot be modified after it is assigned during initialization.



Answer #3    Answered By: Thomas Camaroon     Answered On: May 29

final means that you can't change the object's reference to point to another reference. Where immutable means that actual object's value can't be changed, but you can change its reference to another one.

Concerning the second part of your question (immutability part), the compiler creates a new String object with the value of "Sam", and points the name reference to it.

More interview questions....