Skip to Content
Java Coding Problems
book

Java Coding Problems

by Anghel Leonard
September 2019
Intermediate to advanced
816 pages
18h 47m
English
Packt Publishing
Content preview from Java Coding Problems

55. Switch expressions

Before we have a brief overview of the switch expressions introduced in JDK 12, let's see a typical old-school example wrapped in a method:

private static Player createPlayer(PlayerTypes playerType) {  switch (playerType) {    case TENNIS:      return new TennisPlayer();    case FOOTBALL:      return new FootballPlayer();    case SNOOKER:            return new SnookerPlayer();    case UNKNOWN:      throw new UnknownPlayerException("Player type is unknown");    default:      throw new IllegalArgumentException(        "Invalid player type: " + playerType);  }}

If we forget about default, then the code will not compile.

Obviously, the preceding example is acceptable. In the worst-case scenario, we can add a spurious variable (for example, player), some cluttering break statements, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Coding Problems - Second Edition

Java Coding Problems - Second Edition

Anghel Leonard
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781789801415Supplemental Content