Java 中的字符串:equals vs == [英] Strings in Java : equals vs ==

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

问题描述

可能的重复:
如何比较 Java 中的字符串?

  String s1 = "andrei";
  String s2 = "andrei";

  String s3 = s2.toString();

  System.out.println((s1==s2) + " " + (s2==s3));

给出以下代码为什么第二次比较 s2 == s3 为真?s2.toString() 返回的是什么?实际位置在哪里 (s2.toString()) ?

Giving the following code why is the second comparison s2 == s3 true ? What is actually s2.toString() returning ? Where is actually located (s2.toString()) ?

推荐答案

首先 String.toString 是一个空操作:

First of all String.toString is a no-op:

/**
 * This object (which is already a string!) is itself returned.
 *
 * @return  the string itself.
 */
public String toString() {
    return this;
}

其次,String 常量是 interned,因此 s1 和 s2 在幕后更改为相同的 String 实例.

Second of all, String constants are interned so s1 and s2 are behind the scenes changed to be the same String instance.

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

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