Java程序比较字符串是否相等
要在Java中比较字符串是否相等,请使用equals()
方法。让我们看一些例子,其中我们检查了相同和不同的字符串值。
示例
public class Demo { public static void main(String[] args) { String one = "x"; String two = "x"; if(one.equals(two)) { System.out.println("String one is equal to two i.e. one==two"); }else{ System.out.println("String one is not equal to String two i.e. one!=two"); } }}
输出结果
String one is equal to two i.e. one==two
让我们来看另一个例子。
示例
public class Demo { public static void main(String[] args) { String one = "x"; String two = "y"; if(one.equals(two)) { System.out.println("String one is equal to two i.e. one==two"); }else{ System.out.println("String one is not equal to String two i.e. one!=two"); } }}
输出结果
String one is not equal to String two i.e. one!=two