什么是 Java 字符串池?

正如它的名字所暗示的那样, ** String Pool in java**是存储在 ** [Java Heap Memory](/community/tutorials/java-heap-space-vs-stack-memoryJava Heap Memory vs Stack Memory Difference)中的一组 Strings。

Java 中的 String Pool

Here is a diagram that clearly explains how String Pool is maintained in java heap space and what happens when we use different ways to create Strings. String Pool in Java, string pool, java string pool String Pool is possible only because String is immutable in Java and its implementation of String interning concept. String pool is also example of Flyweight design pattern. String pool helps in saving a lot of space for Java Runtime although it takes more time to create the String. When we use double quotes to create a String, it first looks for String with the same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference. However using new operator, we force String class to create a new String object in heap space. We can use intern() method to put it into the pool or refer to another String object from the string pool having the same value. Here is the java program for the String Pool image:

 1package com.journaldev.util;
 2
 3public class StringPool {
 4
 5    /**
 6     * Java String Pool example
 7     * @param args
 8     */
 9    public static void main(String[] args) {
10        String s1 = "Cat";
11        String s2 = "Cat";
12        String s3 = new String("Cat");
13
14        System.out.println("s1 == s2 :"+(s1==s2));
15        System.out.println("s1 == s3 :"+(s1==s3));
16    }
17
18}

上述方案的结果是:

1s1 == s2 :true
2s1 == s3 :false

推荐阅读: [Java String Class]( / 社区 / 教程 / java-string)

在 String Pool 中创建了多少个字符串?

有时在 Java 面试中,你会被问到一个关于 String 池的问题,例如,下面的陈述中有多少个字符串被创建;

1String str = new String("Cat");

在上述声明中,将创建 1 或 2 个字符串,如果池内已经有字母字母的字符串,那么池内只会创建一个字符串str。如果池内没有字母字母的字符串,那么它首先将在池内创建,然后在堆积空间中创建,因此总共将创建 2 个字符串对象。 阅读: [Java String Interview Questions and Answers](/community/tutorials/java-string-interview-questions-and-answers Java String Interview Questions and Answers)

Published At
Categories with 技术
Tagged with
comments powered by Disqus