java 中的String 和new String 的区别

例如: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
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值