2
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?

More than 1 year has passed since last update.

Java Switchのアロー構文について

Posted at

アロー構文

JavaのSwitch文で使えるアロー構文というものを初めて知ったのでメモに残しておく。

結論

アロー構文「->」を使うことでswitch文の「:」と[break;]を省略することができる。
{}でブロックを作れば複数行の処理も書ける。
String str = "2";
switch(str){
case "1" -> System.out.println("1です");
case "2" -> System.out.println("2です");
case "3" -> {System.out.println("3です①");
      System.out.println("3です②");
      System.out.println("3です③");
      }
}

普通の書き方

String str = "2";
switch(str){
case "1": System.out.println("1です");
    break;
case "2": System.out.println("2です");
    break;
case "3": System.out.println("3です");
    break;
}

何がいいのか

breakの書き忘れを防止したい場合に有効なのだとか。
あとは見た目もすっきりする。

2
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
2
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?