The Java virtual machine's tableswitch and lookupswitch instructions operate only on int data. Because operations on byte, char, or short values are internally promoted to int, a switch whose expression evaluates to one of those types is compiled as though it evaluated to type int. If the chooseNear method had been written using type short, the same Java virtual machine instructions would have been generated as when using type int. Other numeric types must be narrowed to type int for use in a switch.
No two of the case constant expressions associated with a switch statement may have the same value.
Originally posted by Edwin Dalorzo:
Excellent, very enlightening and deep explanation, Adam.
By the way, welcome to Java Ranch
Originally posted by Jim Yingst:
[Stan]: Letting the byte code implementation influence the language syntax is something that really bugs me.
I'm not sure that's what happened here. My guess is that the main influences here were (1) they were retaining C-like behavior wherever they didn't have (or think they had) a good reason to change it, (2) they were scrambling to put in a bunch of other features they thought were important, and (3) switch statements just weren't that big a deal to most people. Nowadays few of us advocate using switch statements much in Java. (I contend there are a few rare cases where they offer better performance than the alternatives, but that's of very minor importance.) Most of the time we'd advocate using the strategy pattern and replacing a switch with a HashMap. I don't know how common that idea might have been back when Java was developed (other than that they'd obviously have used Hashtable instead). Regardless, I don't think improving switch was high on anyone's priorities in the early days; if it were, probably the first thing to do would be to change the syntax to remove the need for break - and that would fly directly against the idea of retaining C-like behavior where possible. Lacking a compelling reason for change here, they left switch alone. That's my guess, anyway.
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koophttps://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton