Conditional Structure
There are kinds of conditional structure in java are as follows:
➢ If
➢ If else
➢ If else if
➢ Nested if
If Statement:
It is a programming conditional structure that if the statement of if is true, a block of code is executed.
Syntax:
if(condition)
{
//code
}
Example to understand the if statement in java
class if {
public static void main(String[] args) {
int marks=92;
if(marks>=80)
{
System.out.println("Excellent");
}
}
}
Output:
Excellent
If -else:
It is a programming conditional structure that if the statement of if is true, a block of code is executed otherwise the else statement is executed.
Syntax :
if (condition)
{
}
else {
}
Example to understand the if else statement in java
class Ifelse{
public static void main(String[] args) {
int A=6;
int area=A*A;
if(area>=25)
{
System.out.println("Area: "+area);
}
else
{
System.out.println("Invalid Area!");
}
}
}
Output:
Area: 36
If - else -if:
It is a programming conditional structure that if the statement of if is true, a block of code is executed otherwise the else if statement is executed and so on.If all if statements are false then the else statement is to be executed.Similarly this conditional structure executes multiple statements.
Syntax:
if(condition){
//block 1
}
else If(condition)
{
//block 2
}
else if(condition)
{
//block 3
}
.
.
.
else{
//block 4
}
Example to understand the if else if statement in java
import java.util.*;
public class ifelseif {
public static void main(String[] args) {
int age;
Scanner obj=new Scanner(System.in);
System.out.print("Enter age: ");
age=obj.nextInt();
if(age>=10&&age<=20)
{
System.out.println("Successful!");
}
else if(age>=25&&age<=30)
{
System.out.println("Successful!");
}
else if(age>=40&&age<=50)
{
System.out.println("Successful!");
}
else
{
System.out.println("Invalid age!");
}
}
}
Output:
Enter age: 34
Invalid age!
Nested if:
A statement within another statement called nested if statement. Inner statement is not checked without outer if statement when outer if loop is true then inner statement is to be executed.
Syntax:
if(condition){
if(condition){
}
else
{
}
}
else{
}
Example to understand the nested if statement in java
import java.util.*;
public class nested {
public static void main(String[] args) {
int marks;
Scanner obj=new Scanner(System.in);
System.out.println("Enter your marks: ");
marks=obj.nextInt();
if(marks>=75)
{
System.out.println("You are eligible for Army");
int height;
Scanner sc=new Scanner(System.in);
System.out.println("Enter your height: ");
height=sc.nextInt();
if(height>=4.5)
{
System.out.println("Congratulations!You have passed!
}
else
{
System.out.println("Sorry!Best of luck for next time");
}
}
else
{
System.out.println("You cannot apply for army");
}
}
}
Output:
Enter your marks:
98
You are eligible for Army
Enter your height:
6
Congratulations!You have passed!
Comments
Post a Comment