1
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】Stringクラス比較時の等価判定・等値判定の判定違いについてノート

Last updated at Posted at 2019-05-23

Sting型変数に文字列の値を格納する時、書き方の違いによってString.equals==の間で判定結果が異なる。忘れないようにノート。

  • newを使う書き方
    • equals -> true
    • == -> false
  • 楽な書き方
    • equals -> true
    • == -> true

newを使う書き方#

一般的にオブジェクト生成する時と同じ書き方

    String str = new String("文字列");

これで値を格納した変数同士を比較する。
(果たして「格納」という言葉の使い方がこれで合ってるのだろうか?)

Main.java
    // オブジェクトを生成
    String cat1 = new String("たま");
    String cat2 = new String("たま");

    // 等価判定と等値判定
    System.out.println(cat1.equals(cat2));
    System.out.println(cat1 == cat2);
出力結果.
true
false

楽な書き方#

基本データ型に値を格納する時と同じ書き方

    String str = "文字列";

これで変数同士を比較する。

Main.java
    // 変数に値を格納
    String cat3 = "みけ";
    String cat4 = "みけ";

    // 等価判定と等値判定
    System.out.println(cat3.equals(cat4));
    System.out.println(cat3 == cat4);
出力結果.
true
true

つまるところ、==演算子を使って文字列同士を比較してしまうと、判定結果が異なってしまうので気をつけようということ。

1
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
1
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?