question:

I wrote the following code on immutable Strings.

public class ImmutableStrings {

    public static void main(String[] args) {
testmethod();
} private static void testmethod() {
String a = "a";
System.out.println("a 1-->" + a);
a = "ty";
System.out.println("a 2-->" + a);
}
}

Output:

a 1-->a
a 2-->ty

Here the value of variable a has been changed (while many say that contents of the immutable objects cannot be changed). But what exactly does one mean by saying String is immutable? Could you please clarify this topic for me?

source : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Before proceeding further with the fuss of immutability, let's just take a look into the String class and its functionality a little before coming to any conclusion.

This is how String works:

String str = "knowledge";

This, as usual, creates a string containing "knowledge" and assigns it a reference str. Simple enough? Lets perform some more functions:

 String s = str;     // assigns a new reference to the same string "knowledge"

Lets see how the below statement works:

  str = str.concat(" base");

This appends a string " base" to str. But wait, how is this possible, since String objects are immutable? Well to your surprise, it is.

When the above statement is executed, the VM takes the value of String str, i.e. "knowledge"and appends " base", giving us the value "knowledge base". Now, since Strings are immutable, the VM can't assign this value to str, so it creates a new String object, gives it a value "knowledge base", and gives it a reference str.

An important point to note here is that, while the String object is immutable, its reference variable is not. So that's why, in the above example, the reference was made to refer to a newly formed String object.

At this point in the example above, we have two String objects: the first one we created with value "knowledge", pointed to by s, and the second one "knowledge base", pointed to by str. But, technically, we have three String objects, the third one being the literal "base" in the concat statement.

Important Facts about String and Memory usage

What if we didn't have another reference s to "knowledge"? We would have lost that String. However, it still would have existed, but would be considered lost due to having no references. Look at one more example below

String s1 = "java";
s1.concat(" rules");
System.out.println("s1 refers to "+s1); // Yes, s1 still refers to "java"

What's happening:

  1. The first line is pretty straightforward: create a new String "java" and refer s1 to it.
  2. Next, the VM creates another new String "java rules", but nothing refers to it. So, the second String is instantly lost. We can't reach it.

The reference variable s1 still refers to the original String "java".

Almost every method, applied to a String object in order to modify it, creates new String object. So, where do these String objects go? Well, these exist in memory, and one of the key goals of any programming language is to make efficient use of memory.

As applications grow, it's very common for String literals to occupy large area of memory, which can even cause redundancy. So, in order to make Java more efficient, the JVM sets aside a special area of memory called the "String constant pool".

When the compiler sees a String literal, it looks for the String in the pool. If a match is found, the reference to the new literal is directed to the existing String and no new String object is created. The existing String simply has one more reference. Here comes the point of making String objects immutable:

In the String constant pool, a String object is likely to have one or many references. If several references point to same String without even knowing it, it would be bad if one of the references modified that String value. That's why String objects are immutable.

Well, now you could say, what if someone overrides the functionality of String class? That's the reason that the String class is marked final so that nobody can override the behavior of its methods.

answered Jul 30 '13 at 8:45
roger_that

3,69983157
 
8  
"If several references point to same String without even knowing it, it would be bad if one of the references modified that String value. That's why String objects are immutable." AND "what if someone overrides the functionality of String class? That's the reason that the String class is marked final so that nobody can override the behavior of its methods." Good explanation! – Gab是好人 Jul 21 '15 at 11:52 
11  
I think this answer is even better than the accepted answer! – Iching Chang Nov 23 '15 at 5:13
5  
this is the best answer – anon Dec 27 '15 at 5:08
1  
Wow. For me.., this is the best explanation. ThankYou for sharing the knowledge.. – Tops Feb 8 '16 at 2:00
    
Agreed, this is the best answer. – Stranger Feb 16 '16 at 19:46

JAVA —— String is immutable. What exactly is the meaning? [duplicate]的更多相关文章

  1. Why string is immutable in Java ?

    This is an old yet still popular question. There are multiple reasons that String is designed to be ...

  2. Why String is immutable in Java ?--reference

    String is an immutable class in Java. An immutable class is simply a class whose instances cannot be ...

  3. Why String is Immutable or Final in Java

    The string is Immutable in Java because String objects are cached in String pool. Since cached Strin ...

  4. 为什么Java中的String是设计成不可变的?(Why String is immutable in java)

    There are many reasons due to the string class has been made immutable in Java. These reasons in vie ...

  5. Java String Class Example--reference

    reference:http://examples.javacodegeeks.com/core-java/lang/string/java-string-class-example/ 1. Intr ...

  6. 【转载】关于Java String, StringBuilder, StringBuffer, Hashtable, HashMap的面试题

    REF: http://blog.csdn.net/fightforyourdream/article/details/15333405 题目是一道简单的小程序,像下面这样:[java] view p ...

  7. Java String类为什么不可变?

    原文地址:# Why String is immutable in Java? 众所周知,String类在Java中是不可变的.不可变类简单地说是实例不可修改的类.对于一个实例创建后,其初始化的时候所 ...

  8. 为什么 String 是 immutable 类

    二哥,你能给我说说为什么 String 是 immutable 类(不可变对象)吗?我想研究它,想知道为什么它就不可变了,这种强烈的愿望就像想研究浩瀚的星空一样.但无奈自身功力有限,始终觉得雾里看花终 ...

  9. Java String 综述(上篇)

    摘要: Java 中的 String类 是我们日常开发中使用最为频繁的一个类,但要想真正掌握的这个类却不是一件容易的事情.笔者为了还原String类的真实全貌,先分为上.下两篇博文来综述Java中的S ...

随机推荐

  1. EasyUI edatagrid插件使用小计

    html片段 <table id="menuview" style="width:100%"> <thead> <tr> & ...

  2. 对比props

    1.在组件中data返回数组对象 2.在父级作用域中写入 (1)prop传值 <btn-grp :buttons="buttons"></btn-grp> ...

  3. java_线程的同步机制

    1.同步代码块: 使用synchronized包住可能会出现安全问题的代码 import static java.lang.Thread.sleep; class Test01{ public sta ...

  4. vue中滚动页面,改变样式&&导航栏滚动时,样式透明度修改

    vue中滚动页面,改变样式&&导航栏滚动时,样式透明度修改.vue <div class="commonHeader" v-bind:class=" ...

  5. react入门(下)

    react生命周期 1. 组件的三个生命周期状态: * Mount:插入真实 DOM * Update:被重新渲染 * Unmount:被移出真实 DOM2. React 为每个状态都提供了两种勾子( ...

  6. HDU - 2102 A计划(双层BFS)

    题目: 可怜的公主在一次次被魔王掳走一次次被骑士们救回来之后,而今,不幸的她再一次面临生命的考验.魔王已经发出消息说将在T时刻吃掉公主,因为他听信谣言说吃公主的肉也能长生不老.年迈的国王正是心急如焚, ...

  7. MySQL和Oracle的比较

    可以从以下几个方面来进行比较: (1) 对事务的提交    MySQL默认是自动提交,而Oracle默认不自动提交,需要用户手动提交,需要在写commit;指令或者点击commit按钮(2) 分页查询 ...

  8. 运维笔记:zabbix的运用(1)安装过程

    前言 如果是用了阿里云或者腾讯云,他们都有各种监控帮我们做好.但是如果是遇到了自己维护自己机房的服务器,那么一些可视化或者监控就很有意义了.监控可能有很多种方案,这里就以比较老牌通吃的zabbix来解 ...

  9. js 循环 js创建数组

    循环 for (var i = 0; i < myArray.length; i++) { console.log(myArray[i]); }; for (var arr in myArray ...

  10. table JS合并单元格

    function _w_table_rowspan(_w_table_id,_w_table_colnum){ _w_table_firsttd = ""; _w_table_cu ...