==和equals方法

阅读量: 1005 编辑

== 和 equals 都是用来判断 是否相等,在编程中使用频率非常高;

一、== 和 equals 的区别

1、== 是比较对象的值(地址)是否相等

2、equals 是比较对象的内容是否相等

案例

s1 = "hello";	// 常量池中

s2 = "hello";	// 常量池中先找有没有"hello",如果有,那么s2直接指向这个"hello"

s1 == s2; 		//true
s1.equals(s2);  //true

// 在堆中 
s3 = new String("hello");  

s1 == s3; 		//false
s1.equals(s3);  //true

二、编程实战

代码的详细解读,可以参考视频教程

package com.qicong.zj.c13;

/**
 * User: 祁大聪
 */
public class S13 {

    public static void main(String[] args) {
        String s1 = "hello"; //常量池,JVM
        String s2 = "hello";

        System.out.println("s1 == s2, " + (s1 == s2));//true
        System.out.println("s1.equals(s2)," + (s1.equals(s2)));//true

        String s3 = new String("hello");//存放于堆中

        System.out.println();
        System.out.println("s1 == s3, " + (s1 == s3));//false
        System.out.println("s1.equals(s3)," + (s1.equals(s3)));//true

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

        String s5 = "helloWorld";

    }
}


爱码岛编程公众号
试卷资料
爱码岛编程小程序
在线刷题
苏ICP备13052010号
©2023 南京匠成信息科技有限公司