• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

Why String Is Immutable?

 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I know string is immutable, everytime a new string would be created. Theoretically i understand..

However why String is immutable? What would happen if Java makes it mutable?

Also, how does the architecture of the string is designed internally ?

Thanks
 
Saloon Keeper
Posts: 6704
161
Android Mac OS X Firefox Browser VI Editor Tomcat Server Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Internally, a String is a char[]. If you're interested in details, check the source code of String.java - it comes with the JDK.

There have been many discussions about this - if you search for "string immutable" you'll find many topics that discuss all aspects of the issue.
 
Saloon Keeper
Posts: 22780
153
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why? Perhaps a Google search might turn up an interview with one of the Java architects about that.

But I can think of a few reasons. One of which is that it facilitates the creating of a String pool, which means that it's less likely that multiple identical Strings will crowd memory. Look up "interning" of Java strings.

Another is likely to be that it normalizes the handling of string objects and explicit string constants. For example in C:

makes it look like you're altering an unalterable constant. You cannot do that in Java.

It would definitely make Java look a lot different if Strings were mutable. Many methods and techniques would probably be changed and I can't forsee the consequences.

And don't forget - not only are Strings immutable. Class java.lang.String is also final.
 
Saloon Keeper
Posts: 12484
269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Internally, a string consists of either a byte array if all its characters can be encoded in Latin-1, or a char array if it contains any characters that must be encoded in UTF-16. Many different string instances may share the same array to preserve memory. For instance, if you make a substring of a string, both instances will use the same array, but the substring will just refer to a smaller part of the array.

If a string was mutable, one could change the contents of the array through a string reference, and all strings sharing the same array would be affected. This means you can break classes that depend on nobody being able to change their internal strings.
 
Tim Holloway
Saloon Keeper
Posts: 22780
153
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Internally, a string consists of either a byte array if all its characters can be encoded in Latin-1, or a char array if it contains any characters that must be encoded in UTF-16. Many different string instances may share the same array to preserve memory. For instance, if you make a substring of a string, both instances will use the same array, but the substring will just refer to a smaller part of the array.



I wouldn't count on that unless the language spec specifically says so. That's an implementation detail and generally implementation can be anything you want as long as you conform to the language requirements. So some brands and/or versions may use radically different internal implementations and they may even have off-cases where the normal rules are set aside in favor of an alternative internal organization - your assertion of compaction to Latin-1 bytes being an example.

In language terms, a String is an immutable atomic object that presents itself as a sequence of Unicode characters. Since applications have no access to what's inside String, what their actual storage format and organization is is immaterial.

Stephan van Hulst wrote:
If a string was mutable, one could change the contents of the array through a string reference, and all strings sharing the same array would be affected. This means you can break classes that depend on nobody being able to change their internal strings.



Yeah, this is a very common problem on other platforms. The String interning function also consolidates ALL string constants from all loaded classes into a single pool, which means that if you could modify them, you could cause random panic.
 
Rancher
Posts: 144
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Joseph Michael wrote:[...] why String is immutable? [...]


As I like to reply to these kind of questions: Because someone decided so for some reason.
Whenever you encounter a Why? question it almost turns out in  a Because! answer. Another option is to asked the opposite: If your question is Why? then ask Why not? - and vice-versa: If your question is Why not? ask Why should it be?.
Often you come up with: It's some arbitrary choice made by some dev for some reason s/he seen worth it.
Just as an real life example: Why noone thought about security and privacy back when the internet was developed? Simple: Because noone seen a need for it as back then only very few had access to it. And they were considered turstworthy. So, that's why it took up to April 2010 before DNS got some security - 15 years after the browser wars and after SSL was introduced. It's just noone seen a potential risk in DNS that made some sort of proving needed. It was considered secure the way it was invented decades ago. And now ask: Why it was developed that way back then? Turn it around: Why wasn't any crypto implemented back then? Cause there was no need for it.
Same goes pretty much for why String is immutable - cause mutable Strings are a pain to work with.
 
Tim Holloway
Saloon Keeper
Posts: 22780
153
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, actually, the Internet was largely developed off the Unix platform, and Unix grew up fairly secure because it spent a lot of time in University data centers where students would regularly prank each other on shared systems. As opposed to Windows which grew up expecting that one person owned the computer and that no one else could connect to it (pre-networking).

However, back then one thing that people didn't expect was that snooping into people's browsing activities was going to end up not only often government-sponsored but government-mandated. So until recently, the worst offences that DNS had to suffer were cache poisoning and DDOS attacks via UDP requests.

With the resurgence of authoritarian regimes world-wide, however, a lot of things that used to be considered as relatively safe have come under surveillance. We know now that not only can data be used in dangerous ways, so can meta-data. When SSL and proxying prevent knowing what actual URL requests are being made to where, then you look at their DNS lookups to see who they're connecting to. So now we're trying to encrypt DNS lookups. And various agencies are fighting to prevent it.
 
Sheriff
Posts: 15989
265
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just a friendly reminder to please try to stay on topic, which was immutability of String.
 
Marshal
Posts: 26104
72
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:If a string was mutable, one could change the contents of the array through a string reference, and all strings sharing the same array would be affected. This means you can break classes that depend on nobody being able to change their internal strings.



And all it would take would be a simple public void setCharAt(int, char) method for that to happen.

But such methods don't exist, and I'm happy that I don't have to make defensive copies of String objects all the time.
 
Joseph Michael
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree that String is immutable..However they can provide an option if somebody wants to explicitly change it via a method...String.setModify ...Else they have to again go for new String.....

Although it is not possible directly they can provide an alternative way...

Not sure what would be the problem if the user is going to take up the risk
 
Paul Clapham
Marshal
Posts: 26104
72
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Joseph Michael wrote:However they can provide an option if somebody wants to explicitly change it via a method...String.setModify ...Else they have to again go for new String.....

Although it is not possible directly they can provide an alternative way...

Not sure what would be the problem if the user is going to take up the risk



If "they" means the people who designed the Java API, then yes, they did provide an option. It's called "StringBuilder" and it's like a String only you can explicitly change it via a method. And yes, the user does take the risk involved in using mutable objects. But there's no reason to inflict that risk on every single person who wants to use a String object in Java.
 
Marshal
Posts: 71019
291
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Paul Clapham wrote:. . . "StringBuilder . . . the user does take the risk involved in using mutable objects. . . .

I usually use StringBuilders as local variables, so they are confined inside a method where nobody can get at them and alter their state, which obviates that particular risk. Since StringBuilder declares a copy constructor, it is easy enough to take a defensive copy.
 
Rancher
Posts: 259
13
Eclipse IDE C++ Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it's considered a best practice to make all objects immutable, so when you need to modify one just make a whole new object and set it as final. when i first started out i never saw the point in doing this, i thought it's just extra work, and i'm never going to accidentally mutate an object.

but now i have started doing multi-threading, and i see this is absolutely needed to help avoid race conditions. the more things that are immutable the better!

my question is since String is immutable already, does the final keyword have any additional effect?
 
Junilu Lacar
Sheriff
Posts: 15989
265
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Making a String reference final essentially makes it read-only. That is, it cannot be reassigned to a different String once it's assigned so yes, it still matters.
 
You got style baby! More than this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic