Java SE 25 Silver (1Z0-827-JPN) 試験 / 演算子と制御構造 ・ 無料問題 1/5
演算子と制御構造 問題1[switch 式および型パターン、レコード・パターンを使用した switch の使用]
次のコードを実行したときの出力を選んでください。
public class Main { static String describe(Object o) { return switch (o) { case Integer i when i > 10 -> "big"; case Integer i -> "int" + i; case String s -> "str" + s.length(); case null -> "null"; default -> "other"; }; } public static void main(String[] args) { System.out.println(describe(42) + " " + describe(5) + " " + describe("abc") + " " + describe(null) + " " + describe(1.5)); }}選択肢
- A.big int5 str3 other other
- B.big int5 str3 null other正解
- C.big int5 str3 と出力された後、NullPointerException が発生する
- D.int42 int5 str3 null other
解説実行して確認済み
switch の case には型パターン (case Integer i) を書け、一致した値は変数 i として使えます。when は追加の条件 (ガード) で、42 は i > 10 を満たすので big、5 は次の case Integer i に一致して int5 です。case は上から順に調べます。case null があるので、null を渡しても NullPointerException にならずに null を返します。1.5 (Double) はどれにも一致しないので default の other です。
この問題の答えは、試験の対象バージョンでコードを実際に実行して確かめています。確かめ方は運営者情報に書いています。
Java SE 25 Silver (1Z0-827-JPN) 試験 の他の分野の無料問題
ここで公開しているのは無料範囲の問題です。無料登録すると、解答の記録・ダッシュボードでの復習ができ、 プレミアムならこの問題セットの全問題と本番形式の模擬試験も解けます。