Java Reference
In-Depth Information
if(number%2 == 0) { // Test if it is even
if(number < 50) { // Output a message if number is < 50
System.out.println("You have got an even number < 50, " + number);
}
} else {
System.out.println("You have got an odd number, " + number); // It is odd
}
Now the message for an even value is only displayed if the value of number is also less than 50.
The braces around the nested if are necessary here because of the else clause. The braces constrain
the nested if in the sense that if it had an else clause, it would have to appear between the braces
enclosing the nested if . If the braces were not there, the program would still compile and run but the
logic would be different. Let's see how.
With nested if s, the question of to which if statement a particular else clause belongs often arises. If
we remove the braces from the code above, we have:
if(number%2 == 0) // Test if it is even
if(number < 50 ) // Output a message if number is < 50
System.out.println("You have got an even number < 50, " + number);
else
System.out.println("You have got an odd number, " + number); // It is odd
This has substantially changed the logic from what we had before. The else clause now belongs to the
nested if that tests whether number is less than 50, so the second println() call is only executed for
even numbers that are greater than or equal to 50. This is clearly not what we wanted since it makes
nonsense of the output in this case, but it does illustrate the rule for connecting else s to if s, which is:
An else always belongs to the nearest preceding if that is not in a separate block,
and is not already spoken for by another else .
You need to take care that the indenting of statements with nested if s is correct. It is easy to convince
yourself that the logic is as indicated by the indentation, even when this is completely wrong.
Let's try the if-else combination in another program:
Try It Out - Deciphering Characters the Hard Way
Create the class LetterCheck , and code its main() method as follows:
public class LetterCheck {
public static void main(String[] args) {
char symbol = 'A';
symbol = (char)(128.0*Math.random()); // Generate a random character
if(symbol >= 'A') { // Is it A or greater?
Search WWH ::




Custom Search