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
相关推荐
李宥小哥2 小时前
C#基础11-常用类
android·java·c#
小许学java3 小时前
数据结构-ArrayList与顺序表
java·数据结构·顺序表·arraylist·线性表
Java 码农4 小时前
Centos7 maven 安装
java·python·centos·maven
harmful_sheep4 小时前
maven mvn 安装自定义 jar 包
java·maven·jar
007php0075 小时前
某大厂跳动面试:计算机网络相关问题解析与总结
java·开发语言·学习·计算机网络·mysql·面试·职场和发展
JH30735 小时前
第七篇:Buffer Pool 与 InnoDB 其他组件的协作
java·数据库·mysql·oracle
皮皮林5516 小时前
订单分库分表后,商家如何高效的查询?
java
Roye_ack6 小时前
【项目实战 Day12】springboot + vue 苍穹外卖系统(Apache POI + 工作台模块 + Excel表格导出 完结)
java·spring boot·后端·excel·苍穹外卖
Code blocks8 小时前
SpringBoot自定义请求前缀
java·spring boot·后端
Jabes.yang8 小时前
Java求职面试:从Spring Boot到Kafka的技术探讨
java·spring boot·面试·kafka·互联网大厂