How have sun made String immutable.Even string buffer and sting builder are final classes ,but they are mutable through final key word the sting has become un-extendable not immutable.Its not an sufficient condition
Say in a code i do this
String s= "Hello";
Here "Hello Bill" will be a new object , as string is immutable .What in the string class actually triggered it, to make this new object .? What is there in sting class that is not in string Buffer due to which we are seeing immutability in only String and wrapper classes. For Reference i have attached String.java and StringBuffer.java
Immutable means that once an instance of a class is created, there is no way to change the value of the member variables of the class. Class String simply doesn't have any methods that let you change the content of the string, so it is immutable.
Strings are actually a special class in Java; the language has special syntax for handling strings.
When you do this:
The compiler will automatically translate that into something like this behind the scenes:
You can see that by compiling a small test program and then decompiling it with the javap tool that's included with the JDK.
So, there is nothing in the String class that causes a new object to be created; this happens because Java has special syntax for concatenating strings with the + operator, which actually gets converted by the compiler to something that uses a StringBuilder.