Logo 
Search:

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

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

Share: 

 

2 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
str.

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"));
System.out.println(str);

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
a

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.

net-informations.com/faq/general/immutable.htm

camaroon

 




Tagged: