【java】==和equals()区别

== 和 equals()的区别?
A: ==
基本类型:比较的是基本类型的值是否相同
引用类型:比较的是引用类型的地址值是否相同
B:equals()
只能比较引用类型,默认比较的是对象的地址值是否相同。
但是,可能被重写,一定要根据实际的情况来看,例如String类的equals()比较字符串内容是否相等。

/*
 * String s = new String(“hello”)和String s = “hello”;的区别
 * 
 * ==:比较引用类型,比较的是地址值
 * equal():默认比较的是地址值。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
    }
}
public class StringDemo3 {
	public static void main(String[] args) {
		String s1 = new String("hello");
		String s2 = new String("hello");
		System.out.println(s1 == s2); // false
		System.out.println(s1.equals(s2)); // true

		String s3 = new String("hello");
		String s4 = "hello";
		System.out.println(s3 == s4); // false
		System.out.println(s3.equals(s4)); // true

		String s5 = "hello";
		String s6 = "hello";
		System.out.println(s5 == s6);// true
		System.out.println(s5.equals(s6));// true
	}
}
/*
 * 看程序写结果
 * 字符串变量相加:先开空间,再加内容
 * 字符串常量相加:先加,再找,没有再开空间
 */
public class StringDemo4 {
	public static void main(String[] args) {
		String s1 = "hello";
		String s2 = "world";
		String s3 = "helloworld";
		String s4 = s1 + s2;
		String s5 = "hello"+"world";
		System.out.println(s4);
		System.out.println(s5);
//		System.out.println(s3 == s1 + s2);// false
//		System.out.println(s3.equals(s1 + s2));// true
//		System.out.println(s3 == "hello" + "world");// true
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值