Why String is Immutable?

J

Jon Haugsand

* Bharath Ganesh
Hi

Could we have a discussion on why String is Immutable?

Do you wonder why we immutability is desireable in the first place?
If not, the discussion is already done. :) String constants are far
more common than any other kind of strings. Anyway, we have
StringBuffer to take care of the other one.
 
J

jan V

Could we have a discussion on why String is Immutable?

Strings are value objects. Value objects should always be immutable. If you
want a different value (different String), you need a different object.

Apart from that, javac was/is written in Java. javac needed to be reasonably
performing. Parsing Java source code involves the generation and
manipulation of lots of Strings *and* StringBuffers. The two classes have
some optimization-driven "incestuous" relationship behind the scenes which
relies on the immutability aspect.

I'm guessing that back in 93-94-95, such concerns were strong enough to make
String immutable simply for those reasons.
 
R

Roedy Green

I'm guessing that back in 93-94-95, such concerns were strong enough to make
String immutable simply for those reasons.

Imagine being an OS working with a string that some other thread was
modifying behind your back. How could you validate anything without
making a copy?
 
B

Bharath Ganesh

I understand that making String immutable, makes it thread safe and
thus imporves performance.

Is there any other reason for making it Immutable?
 
C

Chris Smith

Bharath Ganesh said:
I understand that making String immutable, makes it thread safe and
thus imporves performance.

Is there any other reason for making it Immutable?

Roedy hinted at one, but let me explain further. Java has this thing
called a SecurityManager, and it is responsible for checking that
unprivileged code (for example, an applet) is allowed to do stuff. To
pick one example, applets are typically allowed to contact their server
of origin with sockets, but not other servers. So let's say I write
this:

String hostName = "my.origin.server.com";
Socket s = new Socket(hostName, 1234);

Looks fine. In the second line, the SecurityManager will first check to
be sure that "my.origin.server.com" really is the origin server. Then
it will establish a connection to that server. BUT this only works if
the server name can't change between the security check and establishing
the connection. If String were not immutable, I could do this:

String fakeHostName = "my.origin.server.com";
String realHostName = "evil.server.com";

String hostName = new String(fakeHostName);

new Thread() {
public void run()
{
while (true)
{
hostName.mutateTo(realHostName);
hostName.mutateTo(fakeHostName);
}
}
}.start();

boolean success = false;
while (!success)
{
try
{
Socket s = new Socket(hostName, 1234);
// try talking to evil.server.com

success = true;
}
catch (SecurityException e) { }
}

It might take a while, but eventually, a context switch would happen
between the security check and establishing the connection. When that
happens, security is compromised.

See how that works? It's not impossible to code around, but if String
were mutable it would be a lot bigger pain to write methods that make
proper use of java.security.AccessController.doPrivileged.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
T

Tor Iver Wilhelmsen

Bharath Ganesh said:
Is there any other reason for making it Immutable?

Safety. If step A of a process receives a String and checks it, you
don't want some programmer to modify it before it reaches step B where
it's assumed to have been OKed by A.

(I assume you already have read the String javadocs which state
another reason: The ability to share them.)

If they were mutable, imagine doing

getClass().getName().someModifyingOperation();

Good luck finding that class again, Mr. Classloader.
 
V

Vova Reznik

Bharath said:
Hi

Could we have a discussion on why String is Immutable?

Why not have discussion about why Double is Immutable? :)
Why replacing any digit in number will create another number (not
necessary different)?
 
J

John Currier

Tor said:
Safety. If step A of a process receives a String and checks it, you
don't want some programmer to modify it before it reaches step B where
it's assumed to have been OKed by A.

(I assume you already have read the String javadocs which state
another reason: The ability to share them.)

If they were mutable, imagine doing

getClass().getName().someModifyingOperation();

Good luck finding that class again, Mr. Classloader.

That case could have been easily resolved with the introduction of a
'const' modifier.

John
http://schemaspy.sourceforge.net
 
C

Chris Smith

John Currier said:
That case could have been easily resolved with the introduction of a
'const' modifier.

No doubt there is some possible use of a keyword "const" in Java that
could solve this problem... but it's not the well-known C/C++ use.
What's needed is immutability (the knowledge that something won't
change), and not unmodifiability (the inability to change something).

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
B

Bent C Dalager

That case could have been easily resolved with the introduction of a
'const' modifier.

I'm not sure in what way exactly the introduction of a "const"
modifier could be said to be "easy" :)

Not that I haven't missed it . . .

Cheers
Bent D
 
T

Tor Iver Wilhelmsen

John Currier said:
That case could have been easily resolved with the introduction of a
'const' modifier.

Apart from your optimism in using "easily" and "const" in the same
sentence - not if you mean const in the C++ sense. You can pass a
non-const reference to a const parameter, the keyword only ensures the
method will not modify it.

And C++ lets you cast away const-ness of fields anyway.
 
T

Thomas Hawtin

Tor said:
And C++ lets you cast away const-ness of fields anyway.

There's some obscure rule that something defined as const at
construction has constness cast away, then the result is undefined.

The main thing is const does not mean constant.

Tom Hawtin
 
J

John Currier

Chris said:
No doubt there is some possible use of a keyword "const" in Java that
could solve this problem... but it's not the well-known C/C++ use.
What's needed is immutability (the knowledge that something won't
change), and not unmodifiability (the inability to change something).

How do you define "something won't change"? String is deemed
immutable, but it changes its internal state when someone calls
hashCode() the first time. No, the external behavior didn't change as
a result of the call, but the object did change.

John
http://schemaspy.sourceforge.net
 
C

Chris Smith

John Currier said:
How do you define "something won't change"? String is deemed
immutable, but it changes its internal state when someone calls
hashCode() the first time. No, the external behavior didn't change as
a result of the call, but the object did change.

Clearly, what's meant here by "something won't change" is that no two
moments in time (t0 and t1) can occur such that the object's observable
behavior at t0 will differ from the object's observable behavior at t1.
I didn't think we would need to get that picky here, but there you are.

The C/C++ const keyword does NOT provide this guarantee. It just
provides that some particular actor may not make a modification to an
object's state. Having a pointer to a const object does NOT guarantee
that no one else holds a pointer to that same object without the const
modifier. (Even the local actor guarantee is weak in both languages,
but that's a different matter and more easily fixable.)

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
R

Raymond DeCampo

Chris said:
Clearly, what's meant here by "something won't change" is that no two
moments in time (t0 and t1) can occur such that the object's observable
behavior at t0 will differ from the object's observable behavior at t1.
I didn't think we would need to get that picky here, but there you are.

The C/C++ const keyword does NOT provide this guarantee. It just
provides that some particular actor may not make a modification to an
object's state. Having a pointer to a const object does NOT guarantee
that no one else holds a pointer to that same object without the const
modifier. (Even the local actor guarantee is weak in both languages,
but that's a different matter and more easily fixable.)

I'm not sure that that issue was what the C++ const keyword was designed
to solve. That is, I do not think the intention was to guarantee that
the thing doesn't change. The intention was to allow the client of a
function or method to pass an object and be confident that the function
or method will not modify the object. Further, the object's class
defines what it means to modify the object. This is similar to the use
of Collections.unmodifiableXxx() in Java.

Not that you have said anything to contradict this or indicate that you
fail to understand it. I think we agree that the C++ const semantics
does not prevent an object from changing.

Ray
 
C

Chris Smith

Raymond DeCampo said:
I'm not sure that that issue was what the C++ const keyword was designed
to solve. That is, I do not think the intention was to guarantee that
the thing doesn't change.

I agree with you. Even better yet, I'm quite CERTAIN that immutability
is not what the C++ const keyword was designed for. I'm certain because
I know that Bjarne Stroustroup is a fairly competent person who would
not make such a serious design error. Immutability is, of course,
achievable in C++ simply by writing a class with no mutation methods.

It's John who said:

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
T

Tor Iver Wilhelmsen

John Currier said:
How do you define "something won't change"? String is deemed
immutable, but it changes its internal state when someone calls
hashCode() the first time.

That's caching of a value determined by delayed evaluation. It's
common to postpone computation until needed; in this case, String does
have "immutable" state, but the value is "indeterminate" in relation
to the public API until requested.
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top