equals和==区别

//1.s1和s2分别引用了2个String对象
String s1 = new String("str");
String s2 = new String("str");
System.out.println(s1 == s2);//flase
System.out.println(s1.equals(s2));//true
if (s1.equals(s2)){//打印s1 equals s2
System.out.println("s1 equals s2");  
}
else {            
System.out.println("s1 not equals s2");
}


//s1 与 s2 引用同一个 String 对象
String s1 = "Monday";         
String s2 = "Monday";         
if (s1 == s2){
System.out.println("s1 == s2");//打印s1 == s2
} else{
System.out.println("s1 != s2");
};


//对于基本类型的包装类型,比如Boolean、Character、Byte、Shot、Integer、Long、Float、Double等的引用变量,==是比较地址的,而equals是比较内容的。
int a1=1;
int a2=1;
Integer b1 =new Integer (1);
Integer b2 =new Integer (1);
System.out.println(a1==a2);  //true
System.out.println(b1==b2); //flase,相同的数据类型,但是它们是两个对象 
System.out.println(a1==b1);//true
System.out.println(a1.equals(a2));//编译错误,equals方法 //不能运用与基本类型的比较


//最大范围比较 Integer(-128~127)
//第一种情况
Integer a = 127;
Integer b = 127;
System.out.println(a == b);//true
//第二种情况
Integer a1 = 128;
Integer b1 = 128;
System.out.println(a1 == b1);//flase
System.out.println(a1.equals(b1));//true


//拓展
//intern()方法;检查字符串池里是否存在这么一个字符串,如果存在,就返回池里的字符串;如果不存在,该方法会把这个字符串添加到字符串池中,然后再返回它的引用。
String s5 = "Monday";
String s6 = new String("Monday");
s6 = s6.intern();         
if (s5 == s6){ //打印   s5 == s6         
System.out.println("s5 == s6");  
}
else {            
System.out.println("s5 != s6");  
}
if (s5.equals(s6)){ //打印   s5 equals s6               
System.out.println("s5 equals s6"); 
}
else{             
System.out.println("s5 not equals s6");  
}

//总结
String s1 = "123"; 
String s2 = "123"; 
String s3 = "abc";  
String s4 = new String("123"); 
String s5 = new String("123"); 
String s6 = new String("abc");   
System.out.println(s1 == s2);
//(1)true 
System.out.println(s1.equals(s2));
//(2)true 
System.out.println(s1 == s3);
//(3)flase 
System.out.println(s1.equals(s3));
//(4)flase   
System.out.println(s4 == s5);
//(5)flase 
System.out.println(s4.equals(s5));
//(6)true 
System.out.println(s4 == s6);
//(7)flase 
System.out.println(s4.equals(s6));
//(8)flase   
System.out.println(s1 == s4);
//(9)false  
System.out.println(s1.equals(s4));
//(10)true

//jsp页面,因为是弱语言,在做比较的时候直接取的里面的值
var a = 1;
var b = "1";
if(a == b ){//弹出1
alert(1);
}else{
alert(1);

}

equals是object类的方法,所有没有重写这个方法的类中的这个方法比较的都是地址,也就是和'=='是一样的,重写过这个方法的类就按照重写的方法来比较,比如String类就重写了这个方法,比较的是内容 













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值