Java Design – Benefits of Switching on Strings in Java 7

designjavaswitch statement

When I was starting to programme in Java, the fact that switch statements didn't take strings frustrated me. Then on using Enums, I realised the benefits that you get with them rather than passing around raw values — type safety (which brings easier refactoring) & also clarity to other developers.

I'm struggling to think of a situation where with SE7 I'll now decide to use a switch with strings as inputs rather than Enums. If they are implemented via switching on whole strings (e.g. rather than partial or regex matches), it doesn't seem to offer less reason for the code to change.

And with IDE tools and the read-write ratio of coding, I'd be much happier auto-generating an extra Enum than passing around string values.

What benefit do they bring to us as programmers? Less boiler-plate?

It doesn't feel like the language was crying-out for this feature. Though maybe there's a use-case I'm overlooking.

Best Answer

As far as I can tell, the question is why wrapping String constants into enum hasn't been considered sufficient to cover the needs of language users. This has been addressed in the official feature proposal announced at JDK 7 (project Coin) mailing list.

Per my reading of the proposal, alternative of using enums has been dismissed on the ground that it introduces types bloat. For your convenience, relevant part of the proposal is quoted below, with the statement addressing enums quoted in bold:

MAJOR ADVANTAGE: What makes the proposal a favorable change?

More regular coding patterns can be used for operations selected on the basis of a set of constant string values; the meaning of the new construct should be obvious to Java developers.

MAJOR BENEFIT: Why is the platform better if the proposal is adopted?

Potentially better performance for string-based dispatch code.

MAJOR DISADVANTAGE: There is always a cost.

Some increased implementation and testing complexity for the compiler.

ALTERNATIVES: Can the benefits and advantages be had some way without a language change?

No; chained if-then-else tests for string equality are potentially expensive and introducing an enum for its switchable constants, one per string value of interest, would add another type to a program without good cause...