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
相关推荐
古法安卓6 小时前
Android-epoll原理详解
android·java·android studio
fireworks996 小时前
接口鉴权(401与403)
java·后端
wear工程师7 小时前
线程池里的异常去哪了?execute 和 submit 不是一回事
java
孔明click337 小时前
别人绕过我的网关直接调用资源服务怎么办?使用 Sa-Token 解决:网关转发鉴权、RPC调用鉴权
java·sa-token·springboot·权限·权限认证
吴声子夜歌7 小时前
Java面试——设计模式(一)
java·设计模式·面试
半亩码田7 小时前
C#转Python第3.6篇:Python 的 @property 比 C# 的 get/set 更灵活
java·python·c#
老郑聊AI业财智造7 小时前
Spring AI 技术架构与源码分析
java·人工智能·后端·spring·架构·软件工程
省长7 小时前
别人绕过我的网关直接调用资源服务怎么办?使用 Sa-Token 解决:网关转发鉴权、RPC调用鉴权
java·后端·开源
MetaLite7 小时前
SpringBoot异常处理-到底该转换还是继续抛-入口层与调用层不能一刀切
java·spring boot·后端
赵广陆8 小时前
Spring AI的聊天模型
java·人工智能·spring