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
相关推荐
LUCIAZZZ6 分钟前
Https解决了Http的哪些问题
java·网络·网络协议·spring·http·rpc·https
论迹27 分钟前
【JavaEE】-- 多线程(初阶)2
java·开发语言·java-ee
桃子是唯一的水果35 分钟前
java 单例模式(Lazy Initialization)实现遍历文件夹下所有excel文件且返回其运行时间
java·单例模式·maven
+72037 分钟前
如何在java中用httpclient实现rpc post 请求
java·开发语言·rpc
ybq1951334543139 分钟前
javaEE-SpringBoot日志
java·spring boot·后端
火烧屁屁啦43 分钟前
【JavaEE进阶】图书管理系统 - 贰
java·spring
xzzd_jokelin43 分钟前
Spring AI 接入 DeepSeek:开启智能应用的新篇章
java·人工智能·spring·ai·大模型·rag·deepseek
刘什么洋啊Zz1 小时前
剖析IO原理和零拷贝机制
java·运维·网络
卷心菜好6啊1 小时前
特辣的海藻!2
java
心态与习惯1 小时前
mac 下 java 调用 gurobi 不能加载 jar
java·jar·mac·cplex·gurobi