The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two-way decision statement and is used in conjunction with an expression. It takes the following form -
if(test expression)
It allows the computer to evaluate the expression first and then depending on whether the value of the expression (relation or condition) is 'true' or 'false' it transfers the control to a particular statement. This point of program has two paths to follow, one for the true condition and the other for false condition.
Simple if statement
The general form of simple if statement is
if(test expression)
{
statement-block;
}
statement-x;
The statement block may be a single statement or a group of statements. If the test expression is true, the statement block will be executed; otherwise the statement block will be skipped and the execution will jump to the statement-x. Remember when the condition is true both the statement block and the statement-x will be executed.
Example
public class If1 {
public static void main(String[] args) {
int a=10,b=5;
if(a>b)
{
System.out.println("a is greater");
}
}
}
Output -
a is greater
Explanation
1. Two variables a & b of type int is declared.
2. Variable-a is assigned a value of 10 and variable-b with 5
3. If condition is used to check whether a is greater than b. if(a>b)
4. As a is greater than b the print inside the if{} is executed with a message "a is greater".
else
It is a keyword, by using this keyword we can create alternate block for 'if' condition using 'else' means always optional, it is recommended to use. When we have an alternate block of 'if' condition. When we are working with 'if' and 'else' only one block will be executed and when the if condition is false then only else part will be executed.
No comments:
Post a Comment