如何在 Java 中初始化和比较字符串?
你可以使用 compareTo() 方法或 equals() 方法或 == 运算符比较字符串。以下示例演示如何在 Java 中初始化并比较字符串。
示例
实时演示public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials";
String str2 = "point";
// comparing str1 and str2
int retval = str1.compareTo(str2);
// prints the return value of the comparison
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP