关于 java中string类不能用== 比较问题!大神进!

2025-05-01 00:43:51
推荐回答(3个)
回答1:

s和s1引用的是同一个字符串对象.

其实,JAVA里面存在字符串池这个东西.

String s = "hello";
String s1 = "hello";

这两句只会创建一个"hello"字符串放入串池里面,s和s1只是这个字符串的两个引用而已.

回答2:

楼主并没有理解string pool这个概念
如果String s = new String("hello");
String s1 = new String("hello");
这俩==判断肯定是false
楼主搜索java有意思的知识点 第一个博客里 类似
public static void test() {
String x = "hello";
String y = "world";
String z = new String("helloworld");
String a = "helloworld";
System.out.println("x == hello:" + (x == "hello"));
System.out.println("a == helloworld:" + (a == "hello" + "world"));
System.out.println("a == x+y:" + (a == (x + y)));
}

这个题 你的答案是什么?

回答3:

是这样的 , String s2=new String("hello"); 这样在new 一个对象赋值 内存地址就不一样了,就会返回false