Many a times, we want a set of instructions to be executed in one situation, and an entirely different set of instructions to be executed in another situation. This kind of situation is dealt in Java programs using a decision control instruction.
In decision making structure programmer specifies one or more conditions to be evaluated or checked by the program, on the basis of result i.e. either true or false , statements get executed.
Below is the abstract representation of decision making statement ..
Java programming handles decision-making by supporting the following statements,
1. Simple if Statement
If block contains the condition, if condition is true, then the statement will execute and if the condition is not true then the statement will not execute.
if(boolean_expression){
/*statements will execute if the boolean expression is true */
}
Example:
public class Test
{
public static void main(String []arg)
{
// local variable declaration:
int a = 10;
// check the boolean condition
if( a < 20 ) {
/* if condition is true then print the following */
System.out.print("a is less than 20");
}
System.out.print("\nvalue of a is : "+a);
}
}
Explanation:
Test
. main
method, which is the entry point of the program. a
and initialize it with the value 10. a
is less than 20. If true, it executes the block of code within the if statement.When you run this program, the output will be:
a is less than 20 value of a is : 10
This output confirms that the condition in the if statement is true, so the message "a is less than 20" is printed, followed by the value of a.