String类的equals()方法接受一个String作为参数,并将当前字符串与指定对象进行比较。当且仅当参数不为null并且是一个String对象,表示与此对象相同的字符序列时,结果为true。
import java.lang.*; public class StringDemo { public static void main(String[] args) { String str1 = new String("sachin tendulkar"); String str2 = new String("amrood admin"); String str3 = new String("amrood admin"); //检查是否相等 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 = false str2 is equal to str3 = true