COS 130 Switch break and constants Switch Statement

COS 130 Switch, break, and constants

Switch Statement • An alternative (in some cases) to the if statement • Can only be used with int, single char, short, or byte (Java 7 adds String) • Use break statement to prevent “fall through”

Switch Example switch(num) { case 1: System. out. println("Value is 1"); break; case 2: System. out. println("Value is 2"); break; case 3: System. out. println("Value is 3"); break; default: System. out. println("Should be 1, 2, or 3"); break; }

Switch Statement • We can put the cases in any order • Even the default statement can go in any order • We can take advantage of “fall through” to do the same work for two or more different values

switch(grade) { case 'b': case 'B': System. out. println("Above Average"); break; case 'A': case 'a': System. out. println("Excellent"); break; default: System. out. println("Should be A, B, C, D or F"); break; case 'c': case 'C': System. out. println("Average"); break; case 'D': case 'd': System. out. println("Below Average"); break; case 'f': case 'F': System. out. println("Failing"); break; }

Break statement • Use to skip the rest of a block of code • Almost always needed for switch • May be used to leave block of code in the middle of a loop

Break loop for(int i = 0; i < a. length; i++) { System. out. println(a[i]); if(a[i] > 5) { System. out. println("leave early with break"); break; } }

Break loop while(true) { String cmd = scan. next(); if(cmd. equals("quit")) { System. out. println("got the input"); break; } }

Constants • Allows us to name a value that can not change during program execution • To change the value of a constant the program must be recompiled

Motavation What does this statement do: amount = balance * 0. 069; How about: amount = balance * INTEREST_RATE;
![Motivation What will this array be used for: double rainfall[][] = new double[12]; How Motivation What will this array be used for: double rainfall[][] = new double[12]; How](http://slidetodoc.com/presentation_image_h/244363276fd0dea321ab23f8e86307ba/image-11.jpg)
Motivation What will this array be used for: double rainfall[][] = new double[12]; How about: double rainfall[][] = new double[MONTHS][REGIONS];

Syntax • Similar to a variable declaration, but with the keyword “final” added in front • By convention use all CAPS Examples final double INTEREST_RATE = 0. 069; final int MONTHS = 12;

When To Use • Replace numeric literals – Magic Numbers • Use for values that can not change - PI
- Slides: 13