• Post Reply Bookmark Topic Watch Topic
  • New Topic

why string  RSS feed

 
Hasan
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why string are immutable?
 
Raghavan Muthu
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy Manazirrrrrhasan Khanrrrr ,

Welcome to JavaRanch Great question you have started off with.

My guess goes this way. As such Strings are the basic and main way the inputs are dealt across and considering in terms of the total number of objects being created in heap, they might have done that way.

When the strings are immutable, only the references (handles) are made point to the existing object, and NOT new objects are created.

I hope this could help.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Manazirrrrrhasan Khanrrrr", please check your private messages. You can see them by clicking My Private Messages.
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe this link can help you.

why is String immutable and final?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Remko Strating:
Maybe this link can help you.


Well, if he's interested in utterly missing the point, sure.

The main reason strings are final and immutable is security. If you could change a String over time, then no code could trust the contents of a String, and any method that needed to look at a String would have to make a copy of it before doing anything with it at all. Otherwise the sandbox security model goes right to pieces. For example, what if you could ask for permission to connect to a given server, then later, after you get permission but before the system makes the connection for you, change the String containing the server name to some other server?

If you needed to copy a String to trust it, then not copying a String would be a bug, and people being the way they are, there'd be bugs like this being reported against the Java APIs all the time. Ugh. Not to mention the inefficiency of making all those copies.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hasan - please check your private messages again.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!