浅谈Java中的equals和==

public class Main {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
         
        int n=3;
        int m=3;
         
        System.out.println(n==m);
         
        String str = new String("hello");
        String str1 = new String("hello");
        String str2 = new String("hello");
         
        System.out.println(str1==str2);
         
        str1 = str;
        str2 = str;
        System.out.println(str1==str2);
     
        String str3 = "Hello";
        String str4 = "Hello";
        System.out.println("str3 == str4 : " + (str3 == str4));
    }
 
}   

运行的结果依次为:true false true true

 

  •   对于Java中的基本数据类型,==是直接比较两个的值是否相等。

     对于引用类型的变量,则==是比较所指向的对象的地址。

  •   而equals方法不能作用于基本数据类型的变量!!!

     如果没有对equals方法进行重写,则比较的是引用类型的变量所指向的对象的地址。

 

——————————————————————————————————————

其中,对于String str1 = new String ("hello"); 称作为 引用类型的变量。引用类型的变量存储的并不是 “值”本身,而是于其关联的对象在内存中的地址。

  String str1;

  这句话声明了一个引用类型的变量,此时它并没有和任何对象关联。

  而 通过new String("hello")来产生一个对象(也称作为类String的一个实例),并将这个对象和str1进行绑定:

  str1= new String("hello");

  那么str1指向了一个对象(很多地方也把str1称作为对象的引用),此时变量str1中存储的是它指向的对象在内存中的存储地址,并不是“值”本身,也就是说并不是直接存储的字符串"hello"。这里面的引用和C/C++中的指针很类似。

  因此在用==对str1和str2进行第一次比较时,得到的结果是false。因此它们分别指向的是不同的对象,也就是说它们实际存储的内存地址不同。

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值