LoginSignup
1
1

More than 3 years have passed since last update.

【Java】==とequalsの違い

Posted at

プログラミング勉強日記

2020年11月10日
文字列の比較を行うequalsメソッドと==の使い方について備忘録として簡単にまとめる。

==epualsの違い

 早速本題に入る。int型やchar型などのプリミティブ型で2つの値が等しいかどうかを比較するときは==演算子を使う。String型などの参照型の場合はequalsメソッドで比較する。
 String型などの参照型の場合に==で比較すると、参照先が同じかどうかを比較し、参照先の値が同じかどうかを比較するわけではない。
 実際にサンプルコードで動かしてみる。

サンプルコード
public static void main(String[] args) {
    // String型変数のstr1とstr2を同じ文字列で初期化
    String str1 = "hello";
    String str2 = "hello";

    if(str1 == str2)
        System.out.println("str1=str2 (==で比較) ");
    else
        System.out.println("str1≠str2 (==で比較) ");

    // 同じ文字列を追加
    str1 += "!";
    str2 += "!";

    if(str1 == str2)
        System.out.println("str1=str2 (==で比較) ");
    else
        System.out.println("str1≠str2 (==で比較) ");

    if(str1.equals(str2))
        System.out.println("str1=str2 (equalsで比較) ");
    else
        System.out.println("str1≠str2 (equalsで比較) ");
}
実行結果
str1=str2 (==で比較) 
str1≠str2 (==で比較) 
str1=str2 (equalsで比較) 

 String型変数のstr1とstr2を同じ文字列で初期化して、同じ文字列を追加したところ、==で比較した場合はfalseを返し、equalsメソッドで比較した場合はtrueを返している。String型は宣言時や初期化時には疑似的にプリミティブ型として扱われるが、文字列を追加したときには参照型として使われる。なので、値が同じであっても参照先が違うので==で比較するとfalseを返す。

参考文献

基本型の比較と参照型の比較
【速習Java】”==”と”equals”の違い(否定の方法も解説)

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1