您可以使用equals()
方法检查Java中两个字符串的相等性。此方法将此字符串与指定对象进行比较。当且仅当参数不为null并且是一个String对象,表示与此对象相同的字符序列时,结果为true。
import java.lang.* public class StringDemo { public static void main(String[] args) { String str1 = "Nhooo"; String str2 = "Nhooo"; String str3 = "Hi"; //检查是否相等 boolean retval1 = str2.equals(str1); boolean retval2 = str2.equals(str3); //打印返回值 System.out.println("str2 is equal to str1 = " + retval1); System.out.println("str2 is equal to str3 = " + retval2); } }
输出结果
str2 is equal to str1 = true str2 is equal to str3 = false