`
leonzhx
  • 浏览: 793600 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

What is String literal pool?

阅读更多

What is String literal pool?

How to create a String

There are two ways to create a String object in Java:

  • Using the new operator. For example,
    String str = new String("Hello");.
  • Using a string literal or constant expression). For example,
    String str="Hello"; (string literal) or
    String str="Hel" + "lo"; (string constant expression).

What is difference between these String's creations? In Java, the equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. The equals method compares the content of two objects rather than two objects' references. The == operator with reference types (i.e., Objects) evaluates as true if the references are identical - point to the same object. With value types (i.e., primitives) it evaluates as true if the value is identical. The equals method is to return true if two objects have identical content - however, the equals method in the java.lang.Object class - the default equals method if a class does not override it - returns true only if both references point to the same object.

Let's use the following example to see what difference between these creations of string:

public class DemoStringCreation {

  public static void main (String args[]) {
    String str1 = "Hello";  
    String str2 = "Hello"; 
    System.out.println("str1 and str2 are created by using string literal.");    
    System.out.println("    str1 == str2 is " + (str1 == str2));  
    System.out.println("    str1.equals(str2) is " + str1.equals(str2));  

    
    String str3 = new String("Hello");  
    String str4 = new String("Hello"); 
    System.out.println("str3 and str4 are created by using new operator.");    
    System.out.println("    str3 == str4 is " + (str3 == str4));  
    System.out.println("    str3.equals(str4) is " + str3.equals(str4));  
    
    String str5 = "Hel"+ "lo";  
    String str6 = "He" + "llo"; 
    System.out.println("str5 and str6 are created by using string 
constant expression.");    
    System.out.println("    str5 == str6 is " + (str5 == str6));  
    System.out.println("    str5.equals(str6) is " + str5.equals(str6));

    String s = "lo";
    String str7 = "Hel"+ s;  
    String str8 = "He" + "llo"; 
    System.out.println("str7 is computed at runtime.");		
    System.out.println("str8 is created by using string constant 
expression.");    
    System.out.println("    str7 == str8 is " + (str7 == str8));  
    System.out.println("    str7.equals(str8) is " + str7.equals(str8));
    
  }
}

The output result is:

str1 and str2 are created by using string literal.
    str1 == str2 is true
    str1.equals(str2) is true
str3 and str4 are created by using new operator.
    str3 == str4 is false
    str3.equals(str4) is true
str5 and str6 are created by using string constant expression.
    str5 == str6 is true
    str5.equals(str6) is true
str7 is computed at runtime.
str8 is created by using string constant expression.
    str7 == str8 is false
    str7.equals(str8) is true

The creation of two strings with the same sequence of letters without the use of the new keyword will create pointers to the same String in the Java String literal pool. The String literal pool is a way Java conserves resources.

 

String Literal Pool

String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption. For example

public class Program
{
    public static void main(String[] args)
    {
       String str1 = "Hello";  
       String str2 = "Hello"; 
       System.out.print(str1 == str2);
    }
}

The result is

true

 

Unfortunately, when you use

String a=new String("Hello");

a String object is created out of the String literal pool, even if an equal string already exists in the pool. Considering all that, avoid new String unless you specifically know that you need it! For example

public class Program
{
    public static void main(String[] args)
    {
       String str1 = "Hello";  
       String str2 = new String("Hello");
       System.out.print(str1 == str2 + " ");
       System.out.print(str1.equals(str2));
    }
}

The result is

false true

 

A JVM has a string pool where it keeps at most one object of any String. String literals always refer to an object in the string pool. String objects created with the new operator do not refer to objects in the string pool but can be made to using String's intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added. For example

public class Program
{
    public static void main(String[] args)
    {
        // Create three strings in three different ways.
        String s1 = "Hello";
        String s2 = new StringBuffer("He").append("llo").toString();
        String s3 = s2.intern();

        // Determine which strings are equivalent using the ==
        // operator
        System.out.println("s1 == s2? " + (s1 == s2));
        System.out.println("s1 == s3? " + (s1 == s3));
    }
}

The output is

s1 == s2? false
s1 == s3? true

There is a table always maintaining a single reference to each unique String object in the global string literal pool ever created by an instance of the runtime in order to optimize space. That means that they always have a reference to String objects in string literal pool, therefore, the string objects in the string literal pool not eligible for garbage collection.

 

String Literals in the Java Language Specification Third Edition

 

Each string literal is a reference to an instance of class String. String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions-are "interned" so as to share unique instances, using the method String.intern.

Thus, the test program consisting of the compilation unit:

package testPackage;
class Test {
        public static void main(String[] args) {
                String hello = "Hello", lo = "lo";
                System.out.print((hello == "Hello") + " ");
                System.out.print((Other.hello == hello) + " ");
                System.out.print((other.Other.hello == hello) + " ");
                System.out.print((hello == ("Hel"+"lo")) + " ");
                System.out.print((hello == ("Hel"+lo)) + " ");
                System.out.println(hello == ("Hel"+lo).intern());
        }
}
class Other { static String hello = "Hello"; }

and the compilation unit:

package other;
public class Other { static String hello = "Hello"; }

produces the output:

true true true true false true

This example illustrates six points:

  • Literal strings within the same class in the same package represent references to the same String object.
  • Literal strings within different classes in the same package represent references to the same String object.
  • Literal strings within different classes in different packages likewise represent references to the same String object.
  • Strings computed by constant expressions are computed at compile time and then treated as if they were literals.
  • Strings computed by concatenation at run time are newly created and therefore distinct.

The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.

 

This article originates from http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3

分享到:
评论

相关推荐

    lab_06_literal_pool_

    《Literal Pool:深入理解与应用》 在计算机科学领域,特别是编程语言和系统设计中,"Literal Pool"(常量池)是一个至关重要的概念。它主要用于存储程序中的各种静态数据,如字符串字面量、数字、符号引用等,旨在...

    Python EOL while scanning string literal问题解决方法

    在Python开发过程中,遇到错误提示“EOL while scanning string literal”时,通常意味着在解析字符串字面量时遇到了问题。具体来说,是在解析过程中遇到了行结束符(End Of Line),但字符串还没有被正确地闭合,...

    mysql输出数据赋给js变量报unterminated string literal错误原因

    在JavaScript中,"unterminated string literal"错误通常发生在字符串字面量没有被正确关闭的情况下。这意味着你的字符串在结束引号之前遇到了未预期的字符,导致JavaScript解析器无法确定字符串的结束位置。在这种...

    001-glib-gdate-suppress-string-format-literal-warning.patch

    001-glib-gdate-suppress-string-format-literal-warning.patch 001-glib-gdate-suppress-string-format-literal-warning.patch 001-glib-gdate-suppress-string-format-literal-warning.patch

    javascript string tutorial

    var stringLiteral = "This is a string literal"; ``` 这种类型的字符串主要通过引用进行操作,并且在执行方法时,JavaScript引擎会暂时将其转换为字符串对象来调用相应的方法。 ##### String Object 字符串对象...

    ts-string-literal-enum-plugin:一种仅需单击即可将枚举转换为字符串文字枚举的工具。 用:red_heart_selector:构建

    ts-string-literal-enum-plugin 只需单击一下,即可将枚举转换为字符串文字枚举的工具。 建立 :red_heart_selector: 。用法安装作为VSCode扩展您可以看到 。作为打字稿插件安装套件yarn add ts-string-literal-enum-...

    Literal(2.0)

    "Literal(2.0)"是一个关于ASP.NET 2.0框架中Literal控件的实例教程。Literal控件在Web开发中扮演着重要角色,尤其在处理静态文本或HTML时非常实用。下面我们将深入探讨Literal控件的核心概念、功能以及如何在C#编程...

    Literal控件的使用

    "Literal控件的使用" Literal控件是ASP.NET Web应用程序中的一种常用的服务器控件,用于在Web页面中显示静态文本或动态生成的内容。在本文中,我们将对Literal控件的使用进行详细的介绍,包括其基本概念、使用场景...

    String详解

    使用这种方式创建的字符串会被存储在一个特殊的内存区域——字符串常量池(String Literal Pool)中。如果再次尝试创建相同的字符串字面量,Java会直接引用已存在的字符串对象,而不是创建新的实例。 2. **new...

    A library with 2 functions. StripChars() removes any specifi

    A library with 2 functions. StripChars() removes any ... SplitString() splits a string on one or more individual characters or on an instance of a string contained within the string you want to split.

    class literal & instance.getClass() & Class.forName(String className)

    在Java编程语言中,"class literal"、"instance.getClass()" 和 "Class.forName(String className)" 是三个与类加载和类型查询紧密相关的概念。了解这些概念对于深入理解Java运行时的类加载机制至关重要。 首先,让...

    c字符串,string对象,字符串字面值的区别详解

    ” //simple string literal“” //empty string literal“\nCC\toptions\tfile.[cC]\n” //string literal using newlines and tabs字符字面值: ‘A’ //single quote:character literal字符串字面值: “A” //...

    The Java EE 6 Tutorial Basic Concepts 4th Edition

    What Is a JavaServer Faces Application? 74 JavaServer Faces Technology Benefits 75 Creating a Simple JavaServer Faces Application 77 Further Information about JavaServer Faces Technology 81 ...

    div+Literal控件的定位

    在网页设计中,"div+Literal控件"的定位是一个重要的技术环节,它涉及到前端布局和用户交互体验。本文将详细解析如何通过div元素和Literal控件实现精确定位选项卡,以及处理滚动条出现时的内容展示问题。 首先,`...

    JDT生成代码实例

    我们还定义了一个名为`getString`的方法,该方法接受一个`String`参数并返回一个`String`。方法内部,我们创建了一个新的`String`变量,然后将参数与固定字符串连接,最后返回这个新的字符串。此外,我们还创建了一...

    Java中的String池

    Java中的String池是一个特殊的数据结构,它存储了所有被程序引用的字符串字面量(literal)。当程序创建一个字符串时,如果该字符串在String池中已经存在,则直接返回String池中已有的实例;若不存在,则将其添加到...

    python包管理工具之PIP

    下载get-pip.py后,在已安装python的机器上执行python get-pip.py, 即可安装pip

Global site tag (gtag.js) - Google Analytics