Why String is Immutable?

O

Oliver Wong

Brendan Guild said:
Tim Tyler wrote in
I mean double - as in:

double d = 2.0;
d = d * d;

I regard double variables as mutable.
[...]

I
certainly agree that double variables are mutable. [...]
it is absurd to have mutable
numbers.

Isn't this self-contradicting?

My 2 cents are that "mutable" and "immutable" only makes sense for
objects, and not primitive types. Scheme happens to treat numeric-literals
as objects. Java treats them as primitives. This sidesteps the whole issue
of whether doubles (the primitive type) are mutable or not. Problem solved?

- Oliver
 
B

Brendan Guild

Oliver Wong wrote in
Brendan Guild said:
I certainly agree that double variables are mutable. [...]
it is absurd to have mutable numbers.

Isn't this self-contradicting?

I intended it to be interpreted as follows:
All variables are mutable in Java, except those marked as 'final'. So
we can say:
double q = 2;
q = 3;
Double r = new Double(2);
r = new Double(3);
Where we change q and we change r. But neither of these operations has
any effect on the values themselves. The object that results from new
Double(2) hasn't been mutated and neither has the number 2.

I'm drawing a distinction between a number and a variable where a
double variable holds a number. A variable is mutable; a number isn't.
 
K

Kenneth P. Turvey

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

You are right, operations on a double are not thread-safe.
So: [Snip]
- or -
mark the double/long as volatile

This doesn't really solve the synchronization issue, does it?

I looked into this a little further and the "volatile" keyword really
doesn't make all accesses to that variable atomic. Is this considered a
JVM bug or is it a feature? When I think "volatile" it doesn't mean the
same thing as synchronized to me. It just means that the JVM can't
optimize away accesses to that variable in memory by putting it in a
register. This is the "C" way of looking at it. Is this point of view
still valid in "Java"?

- --
Kenneth P. Turvey <[email protected]>
http://kt.squeakydolphin.com (not much there yet)
Jabber IM: (e-mail address removed)
Phone: (314) 255-2199
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDQdZSi2ZgbrTULjoRAtQjAKDGEQooLz9SYHIEDg9o5krOrdsARwCggZGj
gN88gCc2+QymG/0qZpVPJ7U=
=7L4m
-----END PGP SIGNATURE-----
 
E

E11

No, i don't think volatile means synchronized.

What happens is that for a non-volatile shared object, a thread's
"view" of the object is only "updated" before entering a synchronized
block. Whereas for a volatile object, a thread's "view" of the object
is ensured to be always "updated" (to changes made by another thread).

My definition may not be correct though. Please correct me if i'm
wrong.



Regards,
Edwin
 
E

E11

An object marked as volatile simply means that changes to the object by
one thread is ensured to be always seen by the other threads. Whereas
for a non-volatile object, the other threads may not see the most
updated object; updating is only done before entering a synchronized
block.

Please correct me if i'm wrong.



Regards,
Edwin
 
R

Roedy Green

I looked into this a little further and the "volatile" keyword really
doesn't make all accesses to that variable atomic. Is this considered a
JVM bug or is it a feature? When I think "volatile" it doesn't mean the
same thing as synchronized to me. It just means that the JVM can't
optimize away accesses to that variable in memory by putting it in a
register. This is the "C" way of looking at it.

see http://mindprod.com/jgloss/volatile.html
http://mindprod.com/jgloss/synchronized.html
http://mindprod.com/jgloss/thread.html
http://mindprod.com/jgloss/threadsafe.html
 
R

Roedy Green

My 2 cents are that "mutable" and "immutable" only makes sense for
objects, and not primitive types.

Immutable means cannot change.

So you can have mutable and immutable objects.
mutable and immutable references (using final)
and mutable and immutable primitives, again using final.
 
H

Harry Bosch

Like I said in my post, I wasn't really sure about the volitile issue.
So, again, if the data member is public, and is going to be used in a
multi-threaded environment, synchonize the method, the object, the
class, whatever, and call it a day.

As for immutability...

java.lang.Double objects are Immutable.
double values are mutable.

Making a variable immutable has nothing to do with the 'final'
operator. A final operator means that an variable's reference cannot
be changed after it has been initialized. This does not mean that the
object is immutable.

Immutability basically means that the object's data cannot change
without changing it's reference. If we have a simple class, such as
Double, that has no mutator methods, nor public access to its
encapsulated data (or all internal members variables) then we can
consider the class immutable. The only way to "change" the value of
the Double is to create a new Double object.

If we were to make the Double mutable, it just means that we could just
easily add some sort of mutator method to change it's internal double
value. Though, this is not possible because the class Double is final.

So, if an object is mutable, but the variable pointing to the object is
final, we can still change the data within the object, but we just
can't change the reference.

The reasoning behind these immutable objects is that they are
inherently thread safe. There is also no way a programmer/developer
can accidentally alter the internal value of these immutable objects.

Check out Joshua Blochs "Effective Java" (specifically the chapter
"Favor Immutabililty")
 
T

Tim Tyler

Brendan Guild said:
Tim Tyler wrote in news:[email protected]:
Brendan Guild said:
Tim Tyler wrote in
In the case of double, the syntax sugar of operators can be
applied to the mutable version - and not to the immutable version.

With Strings it's the other way around - it's the mutable version
that is awkward to use; and it's the immutable version that has
all the syntax sugar.
What mutable version of Double do you mean? [...]
I mean double - as in:

double d = 2.0;
d = d * d;

I regard double variables as mutable.

As evidence in favour of that, interpretation, I present the fact
that operations on them are not atomic - and inspecting their value
from a different thread can expose their value changing in the middle
of an update.

I don't understand how your evidence supports your belief, but I
certainly agree that double variables are mutable. I had considered
that you might have meant double variables but rejected it because
Double variables are also mutable in exactly the same way.

java.lang.Double objects are immutable.
 
O

Oliver Wong

Harry Bosch said:
Like I said in my post, I wasn't really sure about the volitile issue.
So, again, if the data member is public, and is going to be used in a
multi-threaded environment, synchonize the method, the object, the
class, whatever, and call it a day.

As for immutability...

java.lang.Double objects are Immutable.
double values are mutable.

Is the double *VALUE* itself mutable (e.g. the value of 2.0 can change),
or is it actually the variable containing the double value mutable (i.e. the
variable foo, which happens to contain the value 2.0 for now, can change)?
This is, of course, just semantic nitpicking, but I get the feeling that's
what the theme of this branch of this thread is all about anyway.
Making a variable immutable has nothing to do with the 'final'
operator.

It depends on your definition of "mutable" and "immutable", of course.
Under Roedy's definition ("mutable" means "can change" and "immutable" means
"cannot change"), then the "final" operator makes the reference it's
operating immutable; whether the object that reference points to is
immutable or not is an entirely different story!

My definition says that "mutable" and "immutable" only make sense for
reference types (i.e. not primitive types), and I don't use the term for
variables themselves. That is, if a variable can only point to one object, I
say that the variable is "final" or "constant", but not that it is
"immutable". But that's just my terminology; you're free to use your own as
long as when we have a discussion, such differences are made clear to avoid
misunderstandings.
A final operator means that an variable's reference cannot
be changed after it has been initialized. This does not mean that the
object is immutable.

I think everyone agrees with the above. They just disagree on when and
where the terms "mutable" and "immutable" are appropriate.
Immutability basically means that the object's data cannot change
without changing it's reference.

I don't require such a tight restriction before saying an object is
immutable, but I agree with the general concept here. I think though, if an
object's internal (private) data changes, but such changes are not ever
visible outside, then the object is still considered immutable.

[ snip the rest, because I think the points presented there were not under
dispute ]

- Oliver
 
B

Brendan Guild

Tim Tyler wrote in
Brendan Guild said:
Tim Tyler wrote in news:[email protected]:
What mutable version of Double do you mean? [...]
I mean double - as in:

double d = 2.0;
d = d * d;

I regard double variables as mutable.

[...] I certainly agree that double variables are mutable. I had
considered that you might have meant double variables but rejected
it because Double variables are also mutable in exactly the same
way.

java.lang.Double objects are immutable.

I mean Double variables - as in:

Double d = new Double(2.0);
d = new Double(d.doubleValue() * d.doubleValue());

I regard Double variables as mutable, considering this one started as
2.0 and ended up as 4.0.
 
D

Dimitri Maziuk

Brendan Guild sez:
Tim Tyler wrote in
Brendan Guild said:
Tim Tyler wrote in What mutable version of Double do you mean? [...]
I mean double - as in:

double d = 2.0;
d = d * d;

I regard double variables as mutable.


[...] I certainly agree that double variables are mutable. I had
considered that you might have meant double variables but rejected
it because Double variables are also mutable in exactly the same
way.

java.lang.Double objects are immutable.

I mean Double variables - as in:

Double d = new Double(2.0);
d = new Double(d.doubleValue() * d.doubleValue());

I regard Double variables as mutable, considering this one started as
2.0 and ended up as 4.0.

Wow. I've got to add this to my signature collection.

Dima
 
E

E11

Roedy said:
So you can have mutable and immutable objects.
mutable and immutable references (using final)
and mutable and immutable primitives, again using final.

Using the final keyword on a variable doesn't make it immutable.

Of course, this is using Java's definition of mutability and
immutablity. An object is immutable if it can't be mutated after
creation. The term "immutable" is closely linked to the term "mutator
methods" (which is how you would normally "mutate" an instance of a
well-written encapsulated class".

Using the final keyword on a variable only means that it cannot be
re-assigned after the initial assignment.

i.e.
final List list = new ArrayList();

list.add("a")
// This is allowed. list is mutated through a mutator method. It is not
immutable.

list = new ArrayList();
// This is not allowed, because of the final keyword. i.e. it cannot be
re-assigned after the initial assignment


Whereas for a (non-final) String (which is immutable)
String s = "a";

s.changeTo("b");
// There is no such method like that allows you to mutate the object
referenced by s (contrast this with the mutable List).

s = "b";
// This re-assignment is allowed as s is not marked as final. However,
this means that s now references a new String object in a new memory
location. The "a" still exist somewhere, and is still "a", and will
still be "a" until it is garbage collected.


Of course, if we have
final String s = "a";
Then s will always reference a String object which will always contain
"a", throughout its lifespan.

i.e. the primitive types, String, and the wrapper to the primitive
types (Integer, Double, etc) are immutable in the Java sense of the
word.

Having the final keyword, and being immutable (or mutable) are very
different concepts.



Regards,
Edwin
 
T

Tor Iver Wilhelmsen

Brendan Guild said:
I regard Double variables as mutable, considering this one started as
2.0 and ended up as 4.0.

Then you are completely missing what the rest of us mean when we say
mutable: that the object can be changed (it has mutators or accessible
fields). By your definition, anything is immutable as long as you
declare a variable final.
 
B

Brendan Guild

Tor Iver Wilhelmsen wrote in
Then you are completely missing what the rest of us mean when we say
mutable: that the object can be changed (it has mutators or
accessible fields). By your definition, anything is immutable as long
as you declare a variable final.

I'm trying to draw a distinction between a variable and an object, but
somehow failing. Obviously Double objects are immutable, so when I say
Double variables are mutable, I mean the variables themselves. By my
definitions any variable is immutable as long as you declare it to be
final; objects are entirely different.

Objects can have setter methods and all kinds of ways to change them
without changing the variable that references them. All I'm trying to
point out is that primitive double values have no such methods. There
is no way to change 2.0 in all variables that hold 2.0 except by
reassigning each of those variables to something else, exactly as if
2.0 was an immutable object. From many practical perspectives, Double
and double are identical; the only difference is syntax.

I had no idea this was controversial.
 
K

Kenneth P. Turvey

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

I'm trying to draw a distinction between a variable and an object, but
somehow failing. Obviously Double objects are immutable, so when I say
Double variables are mutable, I mean the variables themselves. By my
definitions any variable is immutable as long as you declare it to be
final; objects are entirely different.
[Snip]

You're confusing the objects with the references to the objects. Being
able to change the reference to an object to point to another object,
possibly even a completely different type of object, doesn't say
anything about whether the object itself is mutable.

- --
Kenneth P. Turvey <[email protected]>
http://kt.squeakydolphin.com (not much there yet)
Jabber IM: (e-mail address removed)
Phone: (314) 255-2199
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDRHU4i2ZgbrTULjoRAjyAAJsFOISibapSXCcLCfQY4ZeHb8yaqgCg6jwT
MX0NrkrSGiJ5uoagOs4Z3Pk=
=URwJ
-----END PGP SIGNATURE-----
 
B

Brendan Guild

Kenneth P. Turvey wrote in @squeakydolphin.com:
I'm trying to draw a distinction between a variable and an object,
but somehow failing. Obviously Double objects are immutable, so when
I say Double variables are mutable, I mean the variables themselves.
By my definitions any variable is immutable as long as you declare
it to be final; objects are entirely different.
[Snip]

You're confusing the objects with the references to the objects.
Being able to change the reference to an object to point to another
object, possibly even a completely different type of object, doesn't
say anything about whether the object itself is mutable.

I agree with everything said above, both by myself and in Kenneth
Turvey's response. I probably am confused somehow, because I can't see
what in that quote prompted that response. I made no mention of mutable
objects. I even said that objects and references are entirely
different. I believe that I fully understand what an object is and what
a reference is, but I'm beginning to wonder.

Perhaps it is just because I am trying to respond to the strange
assertion that primitive double is some kind of mutable version of
Double that is causing all of my posts to get strange responses.

It seems that it is confusing and dangerous to refer to non-final
variables as mutable and final variables as immutable. Therefore it is
unwise to talk about mutability or immutability of primitive types.
 
H

Harry Bosch

I will concede that it is _probably_ appropriate to call an immutable
primitive as a primitave declared as final.

Though I believe that the concept of mutability is pretty much reserved
for use in the context of objects, and not primitives. Primitive do
not contain mutators. But, now that we get into the auto-boxing, this
distinction is becoming less apparent. So, eventually I believe that
you will be able to call: 9999.toString(); At which point, perhaps
there will be other methods, but I believe that these objects will just
be their equivelants in the java.lang.Number classes. So, they will
also be immutable.

Wow, isn't this one long thread on semantics! I hope i am not angering
anyone. I am just playing along.

So, did anyone actually answer the question as to "Why String is
Immutable"?

The answer is "Because arrays are immutable".
 
Joined
Oct 24, 2010
Messages
13
Reaction score
0
Why String is immutable in Java

String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file by passing name of file as argument to File I/O classes.
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top