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
相关推荐
JIngJaneIL17 分钟前
财务管理|基于SprinBoot+vue的个人财务管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·毕设·财务管理系统
rengang6618 分钟前
352-Spring AI Alibaba OpenAI DashScope 多模态示例
java·人工智能·spring·多模态·spring ai·ai应用编程
不爱学英文的码字机器25 分钟前
深度解析《AI+Java编程入门》:一本为零基础重构的Java学习路径
java·人工智能·后端·重构
不光头强1 小时前
spring IOC
java·spring·rpc
懒羊羊不懒@1 小时前
JavaSe—泛型
java·开发语言·人工智能·windows·设计模式·1024程序员节
JIngJaneIL1 小时前
口腔健康系统|口腔医疗|基于java和小程序的口腔健康系统小程序设计与实现(源码+数据库+文档)
java·数据库·spring boot·小程序·论文·毕设·口腔医疗小程序
Zhang青山1 小时前
使用 Nginx 轻松处理跨域请求(CORS)
java·后端
麦麦鸡腿堡1 小时前
Java的三代日期类(Date,Calendar,LocalDateTime)
java·开发语言
青衫码上行1 小时前
【Java Web学习 | 第四篇】CSS(3) -背景
java·前端·学习
寒山李白3 小时前
IDEA连接MySQL服务器数据库指南
java·数据库·mysql·intellij-idea·idea·database