打印字符串比较结果时出现奇怪的输出 [英] Getting strange output when printing result of a string comparison

查看:36
本文介绍了打印字符串比较结果时出现奇怪的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这条线的问题(在下面评论):

System.out.println("使用 == ::"+s3==s4)

输出 false.

然而,System.out.println(s3==s4) 输出 true.

现在,我无法理解为什么会得到这个结果:

公共类字符串{公共静态无效主(字符串 [] args){String s3="香塔努";字符串 s4=s3;String s1=new String("java");String s2=new String("javaDeveloper");System.out.println("使用相等方法::"+s1.equals(s2));System.out.println("使用相等方法::"+s3.equals(s4));System.out.println("Using == ::"+s3==s4);//问题出在这一行System.out.println(s1+"直接打印从超类自动转换为字符串子类的s2值");System.out.println("直接打印从超类自动转换为字符串子类的s1值"+s2);System.out.println(s3);}}

<前>输出使用等于方法::假使用相等方法::true使用 == :: falsejava直接打印从超类自动转换为字符串子类的s2值直接打印从超类自动转换到字符串子类 javaDeveloper 的 s1 值

解决方案

您缺少一组括号:

System.out.println("使用 == ::" + (s3==s4));

在您的版本中,"Using == ::" + s3 正在通过 ==s4 进行比较,后者不是你想要什么.

一般来说,+具有更高的优先级==,这就是为什么 "Using == ::" + s3==s4 被评估为 ("Using == ::" + s3) == s4.

I am facing a problem with this line (commented below):

System.out.println("Using == ::"+s3==s4)

which outputs false.

However, System.out.println(s3==s4) outputs true.

Now, I am not able to understand why I am getting this result:

public class string {
    public static void main(String[] args){
        String s3="Shantanu";
        String s4=s3;
        String s1=new String("java");
        String s2=new String("javaDeveloper");

        System.out.println("Using Equals Method::"+s1.equals(s2));
        System.out.println("Using Equals Method::"+s3.equals(s4));
        System.out.println("Using == ::"+s3==s4);//Problem is here in this line
        System.out.println(s1+"Directly printing the s2 value which is autocasted from superclass to string subclass ");
        System.out.println("Directly printing the s1 value which is autocasted from superclass to string subclass "+s2);
        System.out.println(s3);
    }
}

Output-Using Equals Method::false
Using Equals Method::true
Using == ::false
java Directly printing the s2 value which is autocasted from superclass to string subclass
Directly printing the s1 value which is autocasted from superclass to string subclass javaDeveloper

解决方案

You're missing a set of brackets:

System.out.println("Using == ::" + (s3==s4));

In your version, "Using == ::" + s3 is being compared via == to s4, which isn't what you want.

In general, + has a higher precedence than ==, which is why "Using == ::" + s3==s4 is being evaluated as ("Using == ::" + s3) == s4.

这篇关于打印字符串比较结果时出现奇怪的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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