File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String" Watch "String" New topic


Sumukh Deshpande
Ranch Hand

Joined: Feb 17, 2008
Posts: 87

Can anybody guide on Why String class is final?
What effect it would have created if it would have not been final?

Thanks in advance.
Harshit Rastogi
Ranch Hand

Joined: Apr 15, 2008
Posts: 131
Not only String but all other Wrapper class are final.
It is because:
1)A standard class is created with standard functionalities.
2)Any function which needs to be override a new class will be created keeping the main functionality intact.
3) String class work on fly-design pattern.

My Techie Blog - Java Questions
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46434
Read through the API and it tells you that Strings are immutable. If it were possible to extend the String class it might cease to me immutable.
It would then be possible to have objects which return true from obj instanceof String and equals but do not return the same hash code all the time. It would also be possible to have two objects which start off returning true from equals and later on return false (or vice versa).

People (and the JVM) use Strings on the assumption they are immutable, so all their old code would be "broken."
Sumukh Deshpande
Ranch Hand

Joined: Feb 17, 2008
Posts: 87

In Kathy's book I fond the explanation sbout the same question:

If several reference variables refer to the same String without even knowing it, it would be very bad if any of them could change the String's value.
You might say, "Well that's all well and good, but what if someone overrides the String class functionality; couldn't that cause problems in the pool?" That's one of the main reasons that the String class is marked final. Nobody can override the behaviors of any of the String methods, so you can rest assured that the String objects you are counting on to be immutable will, in fact, be immutable.

So can anybody please explain on the basis of the above?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Originally posted by Sumukh Deshpande:

So can anybody please explain on the basis of the above?

Not sure what you want, here -- you've got a good explanation already. What more do you want to hear?

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: String
It's not a secret anymore!