Given strings and we have to compare them using equals() and compareTo() method.
给定字符串,我们必须使用equals()和compareTo()方法进行比较。
Java string equals() method
Java字符串equals()方法
Java string equals() method compares the content of two strings, If all characters are the same, it returns
Java字符串equals()方法比较两个字符串的内容,如果所有字符都相同,则返回
true, else it returns false.
是true ,否则返回false 。
Java string compareTo() method
Java字符串compareTo()方法
Java string compareTo() method is called with a string and another string is supplied as an argument, it compares the strings based on the Unicode values of the characters in the strings. It returns a
使用字符串调用Java字符串compareTo()方法,并提供另一个字符串作为参数,它根据字符串中字符的Unicode值比较字符串。 它返回一个
positive number, negative number or 0. If both strings have the same content, it returns 0.
正数 , 负数或0 。 如果两个字符串的内容相同,则返回0 。
Java代码使用equals(),compareTo()和==运算符比较字符串 (Java code to compare the strings using equals(), compareTo() and == operator )
// Comparing Strings with equals() and compareTo()
// methods in Java
public class Main {
public static void main(String[] args) {
//strings
String str1 = new String("ABC");
String str2 = new String("PQR");
//comparing strings using equals() method
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str1));
//comparing strings using == operator
System.out.println(str1 == str1);
System.out.println(str1 == str2);
//comparing strings using compareTo() method
System.out.println(str1.compareTo(str1));
System.out.println(str1.compareTo(str2));
}
}
Output
输出量
false
true
true
false
0
-15
翻译自: https://www.includehelp.com/java-programs/comparing-strings-with-equals-and-compareto-methods-in-java.aspx