Search This Blog

Thursday, 29 December 2011

if Control Statements with example

The if Statement


The if statement encloses some code which is executed only if a condition is true. The general syntax of the if statement is:



if (condition) {
    body-code
}
The if statement has two parts. The condition is a boolean expression which resolves to either true or false. Thebody-code is code that will be executed only if the condition is true. Here is an example of the if statement.
Example
// Returns 0 if s is null
public int getLength(String s) {
    if (s == null) {
        // This line of code is execute only if s is null
        return 0;
    }
    return s.length();
}

The if statement also has an optional else part which encloses some code that is executed only if the condition is false. Here is the general syntax of the if statement with the optional else part:

The if Statement with else

if (condition) {
    body-code
} else {
    else-code
}
The else-code is executed only if condition resolves to false. Here is an example of the if statement with the optionalelse part
Example
// Generates a random number and prints whether it is even or odd
if ((int)(Math.random()*100)%2 == 0) {
    System.out.println("The number is even");
} else {
    System.out.println("The number is odd");
}
The else-code part can also be another if statement. An if statement written this way sets up a sequence ofcondition's, each tested one after the other in top-down order. If one of the conditions is found to be true, the body-code for that if statement is executed. Once executed, no other conditions are tested and execution continues after the sequence. Here is an example of a sequence of if/else/if statements

No comments:

Post a Comment