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】三項演算子の2つの書き方は同じ?違いと「型」の重要ルールを解説

0
Posted at

はじめに

Java 初心者がつまずきやすい
「三項演算子って結局何が違うの?」問題を整理します。


sampleコード

// ①
String admCd = (jrdCd != null) ? Integer.toString(jrdCd) : null;

// ②
String admCd = (jrdCd == null) ? null : Integer.toString(jrdCd);

この2つは同じなのか?

✔ 結論

どちらも動きは同じ!

  • jrdCdnulladmCdnull を代入
  • jrdCdnull でない → Integer.toString(jrdCd) を代入

つまり、

条件の書き方が逆なだけで、結果は同じ。


三項演算子の基本

三項演算子は、1行で書ける if–else です。

変数 = (条件) ? 真の場合の値 : 偽の場合の値;

これは次と同じ意味です。

if (条件) {
    変数 = 真の場合の値;
} else {
    変数 = 偽の場合の値;
}

重要ポイント:型はそろえる

三項演算子には 大事なルール があります。

✅ true 側と false 側の型は同じでなければならない

例:

String s = flag ? "A" : "B";  // OK
int x = flag ? 1 : 2;         // OK

これはOKです。

でも…

String s = flag ? "A" : 3;  // ❌ コンパイルエラー

なぜなら:

  • "A"String
  • 3int

型が違うため、Javaが「どの型にすればいいか決められない」からです。
この「型」というコトを忘れていてエラーになってしまうことがしばしば(;'∀')


今回のコードはなぜOK?

String admCd = (jrdCd != null) ? Integer.toString(jrdCd) : null;
  • Integer.toString(jrdCd)String
  • nullString型に代入可能

つまり両方とも String として扱える ので問題ないようになっている。


まとめ

ポイント 内容
①と②の違い 条件の書き方が逆なだけ
動作 同じ
三項演算子の正体 1行で書ける if–else
重要ルール true側とfalse側の型はそろえる

三項演算子は便利ですが、

  • 読みにくくなるなら if–else を使う
  • 型がそろっているか必ず確認する

この2つを意識すると、バグを防げます。

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?