Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the Java string comparison methods?

Shulou Source: shulou.com Published: 2022-06-02 18:14:49 09月29日 Update

This article introduces the relevant knowledge of "Java string comparison methods". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

In Java, there are three common methods for comparing strings: equals() method, equalsIgnoreCase() method, compareTo() method

equals()

The equals() method compares the two strings individually for each character.

"abc".equals("abc")

equalsIgnoreCase() method

equalsIgnoreCase() method has exactly the same effect and syntax as equals() method, but ignores case

"Abc".equalsIgnoreCase("abc")

returns true

compareTo() method

The compareTo() method compares the sizes of two strings in lexicographical order, based on Unicode values for individual characters in the strings.

String str1 = "a";

String str2 = "A";

System.out.println(str1.compareTo(str2));

output 32

Mistake ==

A lot of people will use == when comparing string == to indicate the comparison of the underlying address.

String str1 = "abc";

String str2 = new String("abc");

System.out.println(str1==str2);

System.out.println(str1.equals(str2));

System.out.println(str1=="abc");

System.out.println(str1.equals("abc"));

false

true

true

true

str1==str2 returns false because the two strings are stored at different addresses. str2 is a copy of str1, but with the same value, so equals

https://java-er.com/blog/java-compare-string/

"Java string comparison methods what" content is introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!

Tags: Method character string same two content address size more knowledge output different practical successful next function dilemma dictionary practical commonly used Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi vpn OPPO Reno Docker Apple