why string is immutable and why all wrapper class are immutable?

By default, all Java classes are mutable i.e contents of their instances can be modified. But there are few advantages that immutability offers ( http://download.oracle.com/javase/tutorial/essential/concurrency/immutable.html), and that's why some classes are made immutable by marking them as final. The classes in question are String and Wrapper classes, and if you think logically about them (any immutable class), then the description in the link provided would start making sense. Let us address each of the two separately: 

String class: 
As mentioned in  SCJP page 433 by Kathy Siera and Bert Bates, as applications grow, its very common to have a lot of redundancy in the String literals for a program. Hence, in order to address this issue, the designers of Java came up with the concept of String pool which improves performance by making efficient use of available memory. But now, as you might imagine, if several reference variables refer to the same String without even knowing it, it would be bad if any of them could change the String's value. Hence, there arose the need of making this String class immutable. 

Wrapper classes: 
One of the objectives of making wrapper classes is to provide a mechanism to treat primitives with activities reserved for objects, like being added to Collections, or returned from a method with an object return value. If you think about a collection, it would often be the case that it is accessed by multiple threads. If the wrapper classes weren't immutable, it would run into the risk of concurrent modification and thus lead to inconsistent states. Thus, in order to avoid conflicts, wrapper classes are made immutable. 

So, in general, whenever you come across an immutable class, it would be logical to think of its instances being used in a concurrent manner. Also, if you do not want your object contents to be modified (one of the reasons being concurrent access), then make the class immutable. 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值