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: 14679

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.