java的字符串字面量

  • 在同一个类中,字符串字面量引用同一个字符串对象。例如:
csharp 复制代码
package com.thb;

public class Demo4 {

    public static void main(String[] args) {
        String world = "world";
        System.out.println(world == "world");
    }

}

运行输出:

csharp 复制代码
true
  • 在同一个包的不同类中,字符串字面量引用同一个字符串对象。例如:
csharp 复制代码
package com.thb;

public class Demo4 {

    public static void main(String[] args) {
        String world = "world";
        System.out.println(world == Another.world);
    }

}


package com.thb;

public class Another {

    public static String world = "world";
}

运行输出:

csharp 复制代码
true
  • 在不同包的类中,字面量引用同一个字符串对象。例如:
csharp 复制代码
package com.thb;

public class Demo4 {

    public static void main(String[] args) {
        String world = "world";
        System.out.println(world == com.thb.bian.BianOther.world);
    }

}

package com.thb.bian;

public class BianOther {

    public static String world = "world";
}

运行输出:

csharp 复制代码
true
  • 用常量表达式拼接的字符串是在编译的时候被计算的,因此作为字符串字面量对待。例如:
csharp 复制代码
package com.thb;

public class Demo4 {

    public static void main(String[] args) {
        String world = "world";
        System.out.println(world == ("wor" + "ld"));
    }

}

运行输出:

csharp 复制代码
true
  • 运行时拼接生成的字符串是被新建的,因此是不同的。例如:
csharp 复制代码
package com.thb;

public class Demo4 {

    public static void main(String[] args) {
        String world = "world";
        String ld = "ld";
        System.out.println(world == ("wor" + ld));
    }

}

运行输出:

csharp 复制代码
false
  • 通过显式调用字符串的intern()方法返回的字符串和以前存在的字符串字面量指向同一个字符串对象。
    当调用字符串的intern()方法的时候,会首先到字符串池中查找,如果找到相同的字符串(是否相同是用equals(Object)方法来判断的),则返回池中字符串的引用;如果没有找到相同的字符串,那么就将本字符串增加到字符串池中,然后返回池中字符串的引用。

例如:

csharp 复制代码
package com.thb;

public class Demo4 {

    public static void main(String[] args) {
        String world = "world";
        String ld = "ld";
        System.out.println(world == ("wor" + ld).intern());
    }

}

运行输出:

csharp 复制代码
true
相关推荐
running up1 分钟前
Spring IOC与DI核心注解速查表
java·后端·spring
YDS8292 分钟前
SpringCloud —— Sentinel详解
java·spring cloud·sentinel
洛阳泰山3 分钟前
快速上手 MaxKB4J:开源企业级 Agentic 工作流系统在 Sealos 上的完整部署指南
java·人工智能·后端
guslegend5 分钟前
SpringSecurity授权原理与实战
java
原来是好奇心7 分钟前
深入Spring Boot源码(七):测试框架原理与最佳实践
java·源码·springboot
embrace999 分钟前
【C语言学习】预处理详解
java·c语言·开发语言·数据结构·c++·学习·算法
山沐与山11 分钟前
【Flink】Flink架构深度剖析:JobManager与TaskManager
java·架构·flink
Hello.Reader14 分钟前
Flink SQL「SHOW / SHOW CREATE」元数据巡检、DDL 复刻与排障速查(含 Java 示例)
java·sql·flink
Doris_LMS17 分钟前
接口、普通类和抽象类
java
重生之我是Java开发战士21 分钟前
【数据结构】优先级队列(堆)
java·数据结构·算法