字符串处理:==的用法 [英] String handling: Usage of ==

查看:81
本文介绍了字符串处理:==的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能否在下面的代码中进行解释:

Could you pls explain on the below code:

我知道 == 会比较引用而不是引用价值 。
但是我不清楚下面的代码到底发生了什么?

I know that == compares the reference and not the values . But I am not clear what exactly is happening on the below code?

    public class StringEquals {
    public static void main(String args[])
    {

        String s1="AB";
        String s2="AB"+"C";
        String s3="A"+"BC";
        if(s1==s2)
        {
            System.out.println("s1 and s2 are equal");
        }
        else
        {
            System.out.println("s1 and s2 are notequal");
        }
        if(s2==s3)
        {
            System.out.println("s2 and s3 are equal");
        }
        else
        {
            System.out.println("s2 and s3 are notequal");
        }
        if(s1==s3)
        {
            System.out.println("s1 and s3 are equal");
        }
        else
        {
            System.out.println("s1 and s3 are notequal");
        }   
    }
    }


推荐答案

在Java中, == 检查两个对象是否完全相同,有时它的行为与您的想法不符。

In Java, == checks if two objects are exactly same thing, sometime it acts not what you think.

String s1 = new String("AB")
String s2 = new String("AB")

尽管 s1 s2 具有相同的内容,但是 s1 == s2 返回 false 。因为它们具有不同的引用,但是 s1 s2 具有相同的值,因此 s1.equals(s2)返回 true

Although s1 and s2 have the same content, but s1 == s2 returns false. Because they have different reference, But s1 s2 have same value so s1.equals(s2) returns true

这篇关于字符串处理:==的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆