File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes why String is final ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "why String is final ?" Watch "why String is final ?" New topic
Author

why String is final ?

yashendra chandrakar
Greenhorn

Joined: Mar 22, 2002
Posts: 22
Hi
friends,
What's the reason behind making String immutable.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Performance. Immutable strings can be placed in a string pool. Final classes and methods don't participate in polymorphism and can be inlined at compile time.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Sonny Gill
Ranch Hand

Joined: Feb 02, 2002
Posts: 1211

I read somewhere that it also has to do something with security. So, someone cant write a String subclass and get at some secret information stored in Strings, something like that...


The future is here. It's just not evenly distributed yet. - William Gibson
Consultant @ Xebia. Sonny Gill Tweets
John Dale
Ranch Hand

Joined: Feb 22, 2001
Posts: 399
Consider

It would be good if nobody could make such a SpyString and pass it into code that might be expected to compare the it to some confidential information, like a password or PIN.
Sayed Ibrahim Hashimi
Ranch Hand

Joined: May 17, 2001
Posts: 148
The String class being final is different then the fact that strings are immutable.
Being final means that the String class cannot be subclassed. And the fact the strings are immutable means that once a String has been created it can't be changed. You can only what the reference points to.
so


SCJP 1.4<br /><a href="http://www.cise.ufl.edu/~sih" target="_blank" rel="nofollow">www.cise.ufl.edu/~sih</a>
John Dale
Ranch Hand

Joined: Feb 22, 2001
Posts: 399
Right. I was trying to speak to the earlier point of subclassing. Since I don't think the question has been answered yet...
One reason for making string immutable:
Suppose a string is passed to an object which needs to save the the information in that string for future use. If the string were not immutable, it would need to make a copy of the information in string, at extra cost in memory and time, or save a reference to the string and run the risk that somebody else will change the value of the string in the future, which is generally unacceptable. Thus we need an immutable String class.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: why String is final ?