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. c# 导出DataSet到excel

    public static bool ExportToExcel_dataSet(string queryNo, string conditions) { bool _bl = false; try ...

  2. vue2.0版本指令v-if与v-show的区别

    v-if: 判断是否加载,可以减轻服务器的压力,在需要时加载. v-show:调整css dispaly属性,可以使客户端操作更加流畅. v-if示例: <!DOCTYPE html> & ...

  3. jQuery 的DOM操作

    DOM创建节点及节点属性 创建元素:document.createElement设置属性:setAttribute添加文本:innerHTML加入文档:appendChild append()前面是被 ...

  4. myslq 5.7 root 默认密码

    sudo sumysqld_safe --skip-grant-tables --skip-networking & UPDATE mysql.user SET password=PASSWO ...

  5. 大写URL转小写

    添加LowercaseRoutesMVC.dll引用.通过“管理—NuGet程序包”搜索LowercaseRoutesMVC,然后点击安装.安装成功后会自动引用LowercaseRoutesMVC.d ...

  6. 在PetaPoco中使用Where in

    之前一直没在意,今天查了很多资料,才知道在petapoco中使用in关键字需要使用命名参数,否则是无效的(或者只查出第一个条件的记录),示例如下: var tags= new string[]{“c1 ...

  7. CREATE TRIGGER - 定义一个新的触发器

    SYNOPSIS CREATE TRIGGER name { BEFORE | AFTER } { event [ OR ... ] } ON table [ FOR [ EACH ] { ROW | ...

  8. Centos7 安装MongoDB的详细过程

    一.简介 MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库和非关系数据库之间的产品 ...

  9. cookie和session的用法用途,执行流程,区别联系

    1.为什么要有cookie/session?在客户端浏览器向服务器发送请求,服务器做出响应之后,二者便会断开连接(一次会话结束).那么下次用户再来请求服务器,服务器没有任何办法去识别此用户是谁.比如w ...

  10. cookie存储位置

    平时各位在做项目时多半时候都会用到客户端的cookie,可大家知道cookie是存储在哪里吗? 首先cookie失效分为2种: 1:设置过期时间失效(只要设置了过期时间cookie就会存储在硬盘里面) ...