Home > Java > javaTutorial > Detailed explanation of the differences between equals(), equalsIgnoreCase() and == in Java

Detailed explanation of the differences between equals(), equalsIgnoreCase() and == in Java

零下一度
Release: 2017-05-23 10:55:45
Original
3176 people have browsed it

用久了C#,在Java中,判断一个字符串还是习惯性的用了==,但是总是不能按照正确的判断分支运行,后来才想起来Java中是有equals的,然后就有引出了equalsIgnoreCase。
这三种的正确运用能对敲代码的时候减少不少烦躁的机会。
一、==
==是最经典的判断,此符号判断的是两个对象的值,即对象的内存地址。

[java]String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2);
[/java]
Copy after login

这两个字符串字符是相同的,但是内存地址不同,用==判断输出结果是:false;
二、equals和equalsIgnoreCase
equals是Object的方法,用来判断两个对象是否相同,在判断字符串时它判断的是两个对象的内容是否相同。
equalsIgnoreCase是String的判断方法,只能判断两个字符串。

[java]
String s1 = new String("abc");
String s2 = new String("Abc");
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
[/java]
Copy after login

上面的例子中,输出结果为:false true
equalsIgnoreCase大小写不敏感 equals大小写敏感。
引申:

如果第一个例子写成这样:

[java]
String s1 = "abc";<
String s2 = "abc";
System.out.println(s1 == s2);
[/java]
Copy after login

输出结果就会是:True。
这是为什么呢?
在声明变量的时候,如果用=直接赋值,此时如果变量池中有相同值的字符串,那么就会直接把这个对象的地址赋给新的变量。
而new String("abc")则会重新生成一个变量地址。

【相关推荐】

1. 分享Java中equals和equalsignorecase的区别及使用实例教程

2. 介绍Java equalsIgnoreCase()方法实例

3. java中equalsIgnoreCase方法的图文实例

The above is the detailed content of Detailed explanation of the differences between equals(), equalsIgnoreCase() and == in Java. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template