相关疑难解决方法(0)

字符串池与常量池

我们来看下面的代码片段:

  String s1 = "Hello";
  String s2 = "Hello"; 
Run Code Online (Sandbox Code Playgroud)

由于实习,两个变量都引用同一个对象.由于字符串是不可变的,因此只创建一个对象并且它们都引用同一个对象.

A constant pool也是一种东西,它包含在类中声明的所有常量(整数,字符串等).它是针对每个班级的.

 System.out.println("Hello");  // I believe this Hello is different from above.
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 是否string pool在常量池中引用常量字符串对象的池?
  2. 如果是,字符串池在整个应用程序中是通用的还是特定于类?

java string jvm constants

20
推荐指数
1
解决办法
8980
查看次数

一个String对象加上另一个String,结果取决于两个String对象的参数

只需在jdk1.8(我的是 jdk1.8.0_60) 中运行以下代码,结果是:

true
false
true,
Run Code Online (Sandbox Code Playgroud)

方法c2()返回false,为什么?

我只想了解运行时常量池。不是比较不同的字符串。

试图

public static void main(String[] args) throws InterruptedException {
        c1();
        c2();
        c3();
    }

    private static void c1() {
        String s1 = new String("a") + new String("b");
        s1.intern();
        String s2 = "ab";
        System.out.println(s1 == s2);
    }

    private static void c2() {
        String s1 = new String("h") + new String("e");
        s1.intern();
        String s2 = "he";
        System.out.println(s1 == s2);
    }

    private static void c3() {
        String s1 = new …
Run Code Online (Sandbox Code Playgroud)

java string

-3
推荐指数
1
解决办法
105
查看次数

标签 统计

java ×2

string ×2

constants ×1

jvm ×1