Java字符串compareTo()方法
您可以使用compareTo()
方法或,equals()
方法或或==运算符比较字符串。下面的示例演示如何在Java中初始化和比较字符串。
示例
public class StringDemo { public static void main(String[] args) { String str1 = "tutorials"; String str2 = "point"; //比较str1和str2- int retval = str1.compareTo(str2); //打印比较的返回值 if (retval < 0) { System.out.println("str1 is greater than str2"); } else if (retval == 0) { System.out.println("str1 is equal to str2"); } else { System.out.println("str1 is less than str2"); } } }
输出结果
str1 is less than str2