4
6

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のequalsメソッドで例外を回避する使い方

Last updated at Posted at 2018-01-16

職場でequalsの使い方をなんとなく調べたところ、ワンランク上の使い方を発見しましたので話します。もうすでにこんなこと知ってるよ!という方は温かい目で見てください。そして間違いがあればご指摘お願いします。

#equalsメソッド
equalsメソッドは、Stringクラスの文字列を比較する際によく使用するかと思います。
その際に私は今までこのように呼び出していました。

equals.java
str.equals("hoge");

しかし、この呼び出し方だとstrがnullの場合、nullからequalsを呼び出すためnullPointerExceptionの例外が発生します。

この例外を回避する方法としてif文でnullチェックをするのもアリですが、少しequalsメソッドを変えるだけで例外を回避できちゃいます。

それがこちらです。

equals.java
"hoge".equals(str);

簡単ですね。strと"hoge"を反対にしているだけです。この呼び出し方だとnullPointerExceptionではなくfalseが返ります。よってnullPointerExceptionの例外が起こることはありません。

#おまけ
今回紹介したのはStringクラスのequalsメソッドですが、Objectクラスのequalsメソッドもあります。

equals.java
Objects.equals(str1,str2);

こちらの説明はまたの機会に。

#最後に
これからはequalsメソッドを使うときは文字列を先にして呼び出したいと思います。

4
6
4

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
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?