Branching Statements

GOCOURSE

Branching Statements

 If statement:

 Use if statement to specify a block of code to be executed, if a specified condition is true.

Syntax:

  if(condition)
{

  //code to be executed

 }


Program:

public class ifstatement1
{
public static void main(String[]args)
{
if(10>5)
{
System.out.println("10 is Greater then");
}
}
}

Output:

10 is Greater then

else statement:

Use the else statement to specify a block of code to be executed ,if the condition is false.

Syntax:

if(condition)
{

 //code to be executed

}
else
{

//code to be executed

}

Program:

public class ifstatement1
{
public static void main(String[]args)
{
int time=12;
if(time<10)
{
System.out.println("12pm is afternoon ");
}
else
{
System.out.println("10am is morning");
}
}
}

Output:

10am is morning

else if statement:

 Use else if statement to specify a new condition ,if the first condition is false.

 Syntax: 

if(condition)
{

//code to be executed

}
elseif
{

//code to be executed

}
else
{

//code to be executed

}

Program:

public class num 
{
public static void main(String[] args)
{
int i = 20;
if (i == 10)
{
System.out.println("i is 10\n");
}
else if (i == 15)
{
System.out.println("i is 15\n");
}
else if (i == 20)
{
System.out.println("i is 20\n");
}
 else
 {
System.out.println("i is not present\n");
 System.out.println("Outside if-else-if");
 }
}
}

Output:

i is 20

 Nested if statements:

Nested if statement is a set of if condition one within another. The inner if  conditions are only executed when the outer if condition is true ,otherwise the else block is executed.

Syntax:

if(condition 1)
{

if (condition 2)
{

True block of statement 1;

}

}

 else
{

false block of condition 1;

}
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send