Java Reference
In-Depth Information
3. The next statement declares a double , named interestRate , but does not initialize it with any value.
4. Next, a switch statement is opened, using the variable loanType as the conditional expression.
This means it will try to match the value of loanType to the values listed in each of the cases.
5. Next, the program will evaluate a series of cases, each in the same way. In the first case , it will com-
pare "Commercial" to "Residential" . Because they are unequal, it will move to the next case .
6. In the second case , it will compare "Commercial" to "Commercial" . This time, because the two
strings are equal, it will evaluate the statements associated with this case.
7. Inside the "Commercial" case, the value of interestRate will be set to 0.062. Then, the break
statement will indicate that the switch statement should be interrupted and no further cases or
statements will be evaluated. Without the break statement, the value of interestRate will be
reassigned to 0.059 and again to 0 following all the statements in the rest of the switch statement.
8. After leaving the switch statement, the print statement will output a line of text to the console.
The string that will be printed is composed of four parts:
String loanType: Commercial
String: loans have an annual interest rate of
double interestRate*100: 0.062*100 = 6.2
String: %.
Altogether, the output will be: “ Commercial loans have an annual interest rate of 6.2%.
comparing switches and if-then statements
Just like for and while loops are similar structures, switches and if-then statements are also easy
to compare. When you are using a switch , you read it the same way as an if-then statement: if the
value matches the case, then do something. So how do you know when to use each one?
As with the other control structures, there will be situations when either one is appropriate and you
can choose according to your own preference. As you continue coding, your experience will tell you
if a problem would be better solved with a switch or not.
In general, you might consider the following criteria:
If you have a single variable that can take multiple values, a switch might be suitable.
If you have multiple variables or conditions to consider, you will probably need an if-then
statement.
If the value you are considering can have a finite number of values, consider using a switch .
If the variable can take any value within a continuous range of numbers, consider an if-then
statement.
As before, try to keep simplicity and clarity in mind whenever you make decisions about how to
code. You want a solution that's simple for you to code, but also as clear to read and understand as
possible, for yourself and others who will have to maintain or reuse your code later.
 
Search WWH ::




Custom Search