I understand String and some wrapper classes of integer etc. are immutable. Can anyone explain the reasoning of making classes immutable? The only thing that I can think of is that the immutable classes are thread safe. Is that the reason?
Sorry! I'll violate my own rules one more time. Boolean, Integer, etc. must be immutable! See Java.lang.reflect package, you will know those are extremely critical. [ February 01, 2002: Message edited by: Roseanne Zhang ]
Joined: Jan 26, 2001
I think that I figured out the reasons. If you take a look at these classes, they are all the basic building blocks of the language, or mostly used classes like Strings. Making these classes immutable can give the compiler maximium capacity to optimize the codes. All these classes are final so they can be inlined without concerns of dynamic binding. Also they can be sure to be thread safe, not just at implementation level, but at the language level, because no operation is allowed to change the value once it is set. This also allows other optimization techniques to be used, such as String Pool pointed out by Cindy, in JVM implementation. [ February 02, 2002: Message edited by: Frank Lin ] [ February 02, 2002: Message edited by: Frank Lin ]
Joined: Nov 14, 2000
1) final class cannot be inherited. Therefore, it is always for static binding. Immutable classes are final, of course, the same here! 2) Boolean/Integer/Long/etc. are not the basic building blocks of Java language. boolean/int/long/etc. are!! If Boolean/Integer/Long/etc. were the basic building blocks of Java language, Java would be dead by now!!! They partially contribute to the slowness of using reflection. 3) Java String class is most famous for its inefficiency. All major coding guideline (including Sun's) will advise use less String class, and use StringBuffer instead. Since whenever you need do something on it, you actually need to build a new one, and put the old one for GC. String literal pooling is just a small remedy for a big disease. Read here for some of the ugliness of Java (String class included): The Java IAQ:Infrequently Answered Questions, read question 12, please. An empty new String() takes 40 bytes!!! That is why C# puts string as a value-type. I'll stop on this thread, no matter you think How wrong I'm, or what kind of flaming war might happen here. I'm quiting now! However, I'll read! Thanks! Roseanne Need Java real project experience? Join our project team here! [ February 02, 2002: Message edited by: Roseanne Zhang ]
Mutable means Changeable ( StringBuffer ) ImMutable means Not Changeable ( String ) For every change that you made to a String will lead to create a new memory space. Example: String test="hai"; // memory is allocated test="hello"; //now memory of "hai" is left and mew memory for "hello" is created. This "hai" memory will be Garbage collected. But this will not happen in StringBuffer, the same memory will be used.