第四章02 字符串比较

"==":比较2个字符串栈内存地址是否相同

范例1:用于比较2个数字地址是否相同

//比较两个数字是否相等
public class StringEquals{
	public static void main(String args[]){
		int num1 = 1;
		int num2 = 1;
	    System.out.println(num1 == num2); //true
	}
}

范例2:比较2个字符串地址是否相同

//使用不同方式生成的字符串,地址不同
public class StringEquals{
	public static void main(String args[]){
		String str1 = "hello";
		String str2 = new String("hello");
		String str3 = str2;
	    System.out.println(str1 == str2); //false
		System.out.println(str1 == str3); //false
		System.out.println(str2 == str3); //true
	}
}

范例2结果内存图分析:

范例3:比较2个字符串内容是否相同

public class StringEquals{
	public static void main(String args[]){
		String str1 = "hello";
		String str2 = new String("hello");
		String str3 = str2;
	    System.out.println(str1.equals(str2)); //true
		System.out.println(str1.equals(str3)); //true
		System.out.println(str2.equals(str3)); //true
	}
}

总结:

比较 “==” 与 equals 的区别
    “==”是java本身提供的关系运算符,可以进行数值比较,如果用在String上表示对象内存地址数值比较,此比较不能用于内容比较;
    “equals”是String类自定义的方法,用于进行字符串内容的比较。
 


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值