LoginSignup
20
19

More than 5 years have passed since last update.

Stringの初期化nullと空文字

Posted at

初投稿です。なにはともあれ知ったことは書いていこうかなと。

Stringを初期化するとき

String str = null;

とするのが通常かと思っていたのですが

String str = "";

としているプログラムがありました。

ググったところ知恵袋によると
http://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q11136894676

>nullで初期化→初期化である。ユーザはnullを入力できない事を利用して、値が無い事を明確化し、後々のプログラムでは値が与えられていないことを前提としたコーディングが求められる。

>空文字で初期化→初期値代入である。デフォルトの値として空文字を使う。また、型推論を利用する場合に文字列型である事を明示するために利用する。

とのこと。

使い分けがあるんですね。

以上!ほぼ引用でした。

20
19
6

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
20
19