JavaSE——字符串常量池(StringTable)

简介: JavaSE——字符串常量池(StringTable)

 

文章目录

  1. 字符串常量池
  2. intern方法
  3. 面试题
  4. 字符串常量池(StringTable)

为了提升性能和减少内存开销,避免字符串的重复创建,JVM维护了一块特殊的内存空间,就是字符串常量池。字符串常量池由String类私有的维护

Java中有两种创建字符串对象的方式:

  1. 直接使用字符串常量进行赋值

public class Test {

public static void main(String[] args) {
    String s1 = "hello";
    String s2 = "hello";
    System.out.println(s1==s2);

}

}
//运行结果:true

  1. 通过new创建String类对象

public class Test {

public static void main(String[] args) {
    String s1 = "hello";
    String s2 = "hello";
    String s3 = new String("hello");
    String s4 = new String("hello");
    System.out.println(s3==s4);
    //运行结果:false
}

}

一道题:

//下面代码将输出什么内容:()

public class SystemUtil{

public static boolean isAdmin(String userId){
    return userId.toLowerCase()=="admin";
}
public static void main(String[] args){
    System.out.println(isAdmin("Admin"));
}

}

  1. intern方法

该方法的作用是手动将创建的String对象添加到常量池中

public class Test {

public static void main(String[] args) {
    char[] chars = new char[]{'h','e','l','l','o'};
    String s1 = new String(chars);
    //s1.intern();
    String s2 = "hello";
    System.out.println(s1==s2);
}
//运行结果:false

}

因此输出:false

public class Test {

public static void main(String[] args) {
    char[] chars = new char[]{'h','e','l','l','o'};
    String s1 = new String(chars);
    s1.intern();
    String s2 = "hello";
    System.out.println(s1==s2);
}
//运行结果:true

}

  1. 面试题

请解释String类中两种对象实例化的区别(JDK1.8中)

String str = "hello"

只会开辟一块堆内存空间,保存在字符串常量池中,然后str共享常量池中的String对象

String str = new String("hello")

会开辟两块堆内存空间,字符串"hello"保存在字符串常量池中,然后用常量池中的String对象给新开辟的String对象赋值

String str = new String(new char[]{'h', 'e', 'l', 'l', 'o'})

现在堆上创建一个String对象,然后利用copyof将重新开辟数组空间,将参数字符串数组中内容拷贝到String对象中

相关文章
|
3月前
|
Java 程序员
StringTable(一)
StringTable(一)
29 1
|
3月前
|
存储 Java
StringTable(三)
StringTable(三)
19 1
|
3月前
|
机器学习/深度学习 存储 Java
StringTable(二)
StringTable(二)
25 1
|
存储 Java API
jvm之StringTable解读(二)
jvm之StringTable解读(二)
|
Java C++
jvm之StringTable解读(三)
jvm之StringTable解读(三)
|
存储 缓存 Oracle
|
存储 缓存 Java
JVM - 深入剖析字符串常量池
JVM - 深入剖析字符串常量池
115 0
|
存储 机器学习/深度学习 Java
StringTable(3)
StringTable
78 0
|
Java 程序员
StringTable (1)
StringTable
75 0
|
Java C++
StringTable(2)
StringTable
72 0