0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Java】同一性と同値性の違い

Last updated at Posted at 2020-06-03

Yuheiです。

最近Java Silverの学習をしていますが、引き続きわからなかった部分があったので、まとめることにしました。

同一性について

==演算子を使って比較する。

左辺と右辺が同じオブジェクトであるかを調べます。

例:変数aと変数bが同じオブジェクトであるかを比較

String a = new String("sample");
String b = new String("sample");
System.out.println(a == b); 

上記の結果は、同じオブジェクトなので、「true」と表示されます。

反対に、下記だと、「false」になる。

String a = new String("sample");
String b = "sample";
System.out.println(a == b); 

以上のように、同一性は、変数同士で同じオブジェクトであるかどうかを比較する。

同値性について

equals演算子を使い、変数内が同じ値(内容)かどうかを比較する。

例:等しい場合

String a = "サンプル";
String b = "サンプル";
System.out.println(a.equals.b);

上記は、変数の中身が一致しているので、「true」と表示します。

逆に「false」と表示するときの場合は、

例:等しくない場合

String a = "サンプル";
String b = "サンプル1";
System.out.println(a.equals.b);

変数aには、「サンプル」と入っているのに対し、変数bには「サンプル1」と入っています。

このような場合、値の中身は一致しないので、「false」となります。

まとめ

同一性で調べるのは、オブジェクト。
同値性で調べるのは、変数の中身。

それぞれ調べる内容は違い、使うメソッドや演算子も違います。

以上です。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?