JavaString为什么是final/不可变的?

Why String is immutable or final in Java

Why String is immutable in java is one of the popular interviewquestion. String is one of the most used classes in any programming language.We know that String is immutable and final in java and java runtime maintains aString pool that makes it a special class.

Why String is immutable in Java?

 

why string is immutable in java, why string is immutable and final injava

Let’s look at some benefits of String immutability, that will help inunderstanding why String is immutable in java.

 

   1.String pool is possible onlybecause String is immutable in java, this way Java Runtime saves a lot of javaheap space because different String variables can refer to same String variablein the pool. If String would not have been immutable, then String interningwould not have been possible because if any variable would have changed thevalue, it would have been reflected to other variables also.

    2.If String is not immutablethen it would cause severe security threat to the application. For example,database username, password are passed as String to get database connection andin socket programming host and port details passed as String. Since String isimmutable it’s value can’t be changed otherwise any hacker could change the referencedvalue to cause security issues in the application.

    3.Since String is immutable,it is safe for multithreading and a single String instance can be shared acrossdifferent threads. This avoid the usage of synchronization for thread safety,Strings are implicitly thread safe.

    4.Strings are used in javaclassloader and immutability provides security that correct class is gettingloaded by Classloader. For example, think of an instance where you are tryingto load java.sql.Connection class but the referenced value is changed tomyhacked.Connection class that can do unwanted things to your database.

    5.Since String is immutable,its hashcode is cached at the time of creation and it doesn’t need to becalculated again. This makes it a great candidate for key in a Map and it’sprocessing is fast than other HashMap key objects. This is why String is mostlyused Object as HashMap keys.

 

    Above are some of the reasonsI could think of that shows benefits of String immutability. It’s a greatfeature of Java String class and makes it special.


from:http://www.journaldev.com/802/string-immutable-final-java  

Pankaj




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值