InterviewSolution
| 1. |
Why Is String Class Final In Java? |
|
Answer» Since String is immutable, whenever you perform any operation on string which alters its content a new string OBJECT is created containing the modified string. Which means all the methods of the String class that modify the content in any way return a new String object with the modified content. Now, What if you can OVERRIDE the method of the String class so that it modifies and return the original string reference itself? In that case all the other strings having the same data in the string pool will also get affected as the reference is SHARED for the String literals having the same content. To avoid these kind of SCENARIOS String class is declared as final and it can’t be overridden. Since String is immutable, whenever you perform any operation on string which alters its content a new string object is created containing the modified string. Which means all the methods of the String class that modify the content in any way return a new String object with the modified content. Now, What if you can override the method of the String class so that it modifies and return the original string reference itself? In that case all the other strings having the same data in the string pool will also get affected as the reference is shared for the String literals having the same content. To avoid these kind of scenarios String class is declared as final and it can’t be overridden. |
|