You are on page 1of 4

Control Statements in Java:

Normally, statements in a program are executed one after the other in the order in which they
are written. This process is called sequential execution. Various Java statements, which we
will soon discuss, enable you to specify that the next statement to execute is not necessarily
the next one in sequence. This is called transfer of control.

1) If Statement
It checks whether the condition is true or false and if the condition is true then the if
statement is executed.

Syntax:
if (condition)
{
// Executes this block if condition is true
}

Flowchart:

Example of if statement:

public class IfStatementExample {


public static void main(String args[]){
int studentGrade=70;
if( studentGrade >= 50 ){
/* This println statement will only execute,
if the above condition is true */
System.out.println("Passed");
}
}
}
2) If else Statement
It examines the condition and if the condition is false then else statement is executed.

Syntax:
if (condition)
{
// Executes this block if condition is true
}
else
{
// Executes this block if condition is false
}
Flowchart:

Example of if else statement:


import java.util.Scanner;
public class IfElseExample {
public static void main(String[] args){
Scanner input = new Scanner( System.in );
System.out.print( "Enter The Number: " );
int number = input.nextInt();
input.close();
if(number > 0)
{
System.out.println(number+" is a positive number");
}
else
{
System.out.println(number+" is a negative number");
}
}
}
3) Nested-If Statements
A nested if statement means there is an if or if-else statement within an if statement(s).
This statement is used when we need to check multiple conditions.

Syntax:
if (condition_1)
{
// Executes this block if condition is true
}
else if (condition_2)
{
// Executes this block if condition is true
}
.
.
else
{
// Executes when none of the previous conditions is true
}

Flowchart:
Example of nested-if statement:
public class NestedIfExample {
public static void main(String args[]){
int num=3456;
if(num <100 && num>=1) {
System.out.println("Its a two digit number");
}
else if(num <1000 && num>=100) {
System.out.println("Its a three digit number");
}
else if(num <10000 && num>=1000) {
System.out.println("Its a four digit number");
}
else if(num <100000 && num>=10000) {
System.out.println("Its a five digit number");
}
else {
System.out.println("number is not between 1 & 99999");

}
}
}

Homework:
1) Write down a Java program to find the average of two grads and if the average
greater than or equal 50 then print out the average and "passed".
2) Write down a Java program to check if a number is even or odd.
3) Write down a Java program to find the largest of three numbers.

You might also like