We can compare Strings in Java based on content and reference.
It is used for authentication (via the equals() method), sorting (via the compareTo() method), reference matching (via the == operator), etc.
Three ways to compare Strings in Java:
By using the equals() method
By using the == operator
By comparingTo() method
The equals() method of the String class compares the original contents of the string. It compares string values for equality. The String class provides the following two methods:
public boolean equals(Object another) Compares this string with the specified object.
public boolean equalsIgnoreCase(String another) Compares this string to another string, ignoring case.
Test string comparison 1.java
类 测试字符串比较1{ 公共静态无效 主要(字符串参数[]){ 字符串 s1= "萨钦" ; 字符串 s2= "萨钦" ; 字符串 s3=新 字符串(“萨钦” ); 字符串 s4= "Saurav" ; System.out.println(s1.equals(s2)); //真的 System.out.println(s1.equals(s3)); //真的 System.out.println(s1.equals(s4)); //错误的 } }
Output:
真的 真的 错误的
In the above code, use the equals() method of the String class to compare Two strings. The result is printed as a boolean value, true or false.
Test string comparison 2.java
类 测试字符串比较2{ 公共静态无效 主要(字符串参数[]){ 字符串 s1= "萨钦" ; 字符串 s2= "SACHIN" ; System.out.println(s1.equals(s2)); //错误的 System.out.println(s1.equalsIgnoreCase(s2)); //真的 } }
Output:
错误的 真的
In the above program, the String class method is used. The equals() method returns true if the String objects match and the two strings have the same case. equalsIgnoreCase() returns true regardless of string case.
== operator compares references instead of values.
Test string comparison 3.java
类 测试字符串比较3{ 公共静态无效 主要(字符串参数[]){ 字符串 s1= "萨钦" ; 字符串 s2= "萨钦" ; 字符串 s3=新 字符串(“萨钦” ); System.out.println(s1==s2); //true(因为两者都引用同一个实例) System.out.println(s1==s3); //false(因为s3是指在非池中创建的实例) } }
Output:
真的 错误的
String The class compareTo() method compares values lexicographically and returns an integer value that describes whether the first string is less than, equal to, or greater than the second string.
Assume s1 and s2 are two String objects. If:
s1 == s2: This method returns 0.
s1 > s2: This method returns a positive value.
s1 < s2: This method returns a negative value.
Test string comparison 4.java
类 测试字符串比较4{ 公共静态无效 主要(字符串参数[]){ 字符串 s1= "萨钦" ; 字符串 s2= "萨钦" ; 字符串 s3= "拉坦" ; System.out.println(s1.compareTo(s2)); //0 System.out.println(s1.compareTo(s3)); //1(因为s1>s3) System.out.println(s3.compareTo(s1)); //-1(因为 s3 < s1 ) } }
Output:
0 1 -1
The above is the detailed content of What are the methods of Java string comparison?. For more information, please follow other related articles on the PHP Chinese website!