- Can switch on any byte, short, int, char, String and enumeration.
- Note: can not switch on long or floating point numbers
- Equivalent to if-else if ladder
- More efficient that if-else if ladder in many cases
int count = kb.nextInt(); double price = 0; double taxRate; switch(count) { case 1: price = 1.0; taxRate = 2.0; break; case 2: price = 0.75; case 3: if (price == 0) price = 0.5; taxRate = 1.25; break; default: price = 0.25; taxRate = 1.0; }
Equivalent if-else if ladder
if (count == 1) { price = 1.0; taxRate = 2.0; } else if (count == 2) { price = 0.75; taxRate = 1.25; } else if (count == 3) { price = 0.5; taxRate = 1.25; } else { price 0.25; taxRate = 1.0; }
© 2017, Eric. All rights reserved.