Java String equals()方法

2019-10-16 22:21:45

Java String equals()方法將此字串與指定的物件進行比較。當且僅當引數不為null並且是表示與此物件相同的字元序列的String物件時,結果才為true

語法

以下是此方法的語法 -

public boolean equals(Object anObject)

引數

  • anObject - 要比較的物件。

返回值

  • 如果與String引數值相等,則此方法返回true; 否則返回false

範例

public class Test {

   public static void main(String args[]) {
      String Str1 = new String("This is really not immutable!!");
      String Str2 = Str1;
      String Str3 = new String("This is really not immutable!!");
      boolean retVal;

      retVal = Str1.equals( Str2 );
      System.out.println("Returned Value = " + retVal );

      retVal = Str1.equals( Str3 );
      System.out.println("Returned Value = " + retVal );
   }
}

執行上面範例程式碼,得到以下結果:

Returned Value = true
Returned Value = true