switch Conditionals

A common programming practice in any language is to test a variable against some value, and if it doesn't match, test it again against a different value, and so on. This process can become unwieldy if you're using only if statements, depending on how many different values you have to test. For example, you might end up with a set of if statements something like the following:

if (operation == '+')
    add(object1, object2);
else if (operation == '-')
    subtract(object1, object2);
else if (operation == '*')
    multiply(object1, object2);
else if (operation == '/')
    divide(object1, object2);

This use of if statements is called a nested if statement, because each else statement contains another if until all possible tests have been made. ...

Get Sams Teach Yourself Java 2 in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.