机器学习与数据挖掘Java

java 中的String 和new String 的区别

2020-01-22  本文已影响0人  叫我老村长

例如:String s = new String(“hello”)和String s = “hello”;

内存中有区别,
String str = "hello" 如果之前有String对象是hello的值的话那str直接就指向之前的那个对象了,不再重新new一个对象了
String str = new String("hello");无论以前有没有都重新new一个新的

再写一个测试的例子:

public class StringTest {
public static void main(String[] args) {

String str1="abx";
String str2="abx";
String str3=new String("abx");
String str4=new String("abx");
System.out.println(str1==str2);
System.out.println(str2==str3);
System.out.println(str3==str4);
}

}
结果:
true
false
false
当String str1="abx" "abx"是一个对象
String str2="abx"明显是有声明了一个到“abx”的一个引用str2
所以测试str1==str2时打印true
但String str3=new String("abx");这是显示的创建了一个String对象。判断==时,显然两个对象不是同一个对象。所以判断字符相等的时候我们都用equals方法。也是这个道理。

public class StringDemo2 {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = "hello";

    System.out.println(s1 == s2);// false
    System.out.println(s1.equals(s2));// true
}

}

上一篇下一篇

猜你喜欢

热点阅读