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?

Java における等価比較演算子

0
Posted at

Java では、等価比較演算子として「等価演算子 (==)」と「非等価演算子 (!=)」の2つが提供されています。次に、さまざまな状況で等価演算子がどのように動作するかを見ていきましょう。

等価演算子 (==)

1. プリミティブ型の比較

  • Java には 8 つのプリミティブ型があります:byte、short、int、long、float、double、boolean、char
  • プリミティブ型の場合、比較は実際の値に基づいて行われます
  • 例:
char char1 = 'a';
char char2 = 'a';
System.out.println(char1 == char2);  // trueが出力されます

2. 参照型の比較

  • 参照型の場合、比較はメモリアドレスに基づいて行われます
  • Stringの例を使ってこれを確認してみましょう:

ケース 1:new キーワードを使用する場合

String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2);  // falseが出力されます

falseが出力されます。なぜなら、new String() を使用すると、Java はヒープメモリ上に別々のオブジェクトを作成するからです。同じ内容("Hello")を持っていても、それぞれ異なるメモリアドレスを持つ別のオブジェクトとなります。

ケース 2:文字列リテラルを使用する場合

String str1 = "Hello";
String str2 = "Hello";
System.out.println(str1 == str2);  // trueが出力されます

trueが出力されます。なぜなら、文字列リテラルで使うと、Java は文字列の最適化のための特別なメモリエリアである String Pool を利用するからです。同じ文字列がすでにプール内に存在する場合、Java は新しいオブジェクトを作成する代わりにその既存のオブジェクトを再利用します。そのため、str1 と str2 はどちらも同じ String Pool 内のオブジェクトを参照しています。

重要な注意点

文字列の内容を比較する場合は、== 演算子ではなく .equals() メソッドを使用してください。.equals() メソッドは、文字列がどのように作成されたか(new String() で作成された場合でも、String Pool を使用した場合でも)に関わらず、文字列の内容を正しく比較します。

String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1.equals(str2));  // trueが出力されます
String str1 = "Hello";
String str2 = "Hello";
System.out.println(str1.equals(str2));  // trueが出力されます

非等価演算子(!=)

非等価演算子の結果は等価演算子(==)の結果と逆になりますが、比較の基準は同じです。プリミティブ型は値で比較され、参照型はメモリアドレスで比較されます。

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?