LoginSignup
0
0

switch文でのアロー構文

switch文でアロー演算子を用いたコードを初めて見たのでメモとして残しておく。

アロー演算子「->」を使うことでswitch文の「:」と[break;]を省略することができる。
{}でブロックを作れば複数行の処理も書ける。
String str = "B";
switch(str){
case "A" -> System.out.println("A");
case "B" -> System.out.println("B");
case "C" -> {System.out.println("C");
      System.out.println("D");
      System.out.println("E");
      }
}

普通の書き方

String str = "B";
switch(str){
case "A": System.out.println("A");
    break;
case "B": System.out.println("B");
    break;
case "C": System.out.println("C");
      System.out.println("D");
       System.out.println("E");
    break;
}

何がいいのか

  • breakの書き忘れを防止したい場合に有効。
  • 見た目もすっきりする。
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