Java Conditional Statements || Java example

 

Java Conditional Statements:

We use few conditions in programming to make some operations possible like we need to test a condition and execute a block of code only if the condition is true or false i.e., if our condition is satisfied.

 

In this part of the tutorial on Java Conditional Statements we will look into if else condition

 

Scenario:

We want to check whether age of the user is above 20 years and if yes we can allow him to create a account.

 

if(condition){

/*
*Block of code executed here if condition is true

*/

} else{ 

if false this block is executed

}

 

 

public static int userAge;

public static void main(String args[]) {

    userAge = 35;

    if (userAge > 20)
        System.out.println("User is eligable to create a account");
    else
        System.out.println("User is not eligable to create a account");

}

 

Now we might have multiple conditions to be tested and execute accordingly we can use multiple if conditions

 

First condition

if(condition){

}else{

}

 

Second Condition

if(condition){

}else{

}

 

This type of declaration will do the task but its not a proper way of dealing these condition we might face both memory and time consumption and may result in bad programming practice so to avoid this

 

We will the floor in which user wants to go in a lift scenario

 

public static int floor;

public static void main(String args[]) {

    floor = 2;

    if (floor == 0)
        System.out.println("You are in ground floor");
    else if(floor == 1)
        System.out.println("You are in first floor");
    else if(floor == 2)
        System.out.println("You are in second floor");
    else
        System.out.println("Floor not available");

}

 

Java Conditional Statements

 

if the user enters a floor greater than 2 then default condition is executed

 

floor = 4;

 

if (floor == 0)
    System.out.println("You are in ground floor");
else if(floor == 1)
    System.out.println("You are in first floor");
else if(floor == 2)
    System.out.println("You are in second floor");
else
    System.out.println("Floor not available");

 

Java Conditional Statements

Any query’s on Java Conditional Statements  let us know in the comment section below.

Do like and share for more interesting tutorials.

Show Buttons
Hide Buttons
Read previous post:
Java Relational Operators || Java example

Java Relational Operators : Relationship operators are used to compare variables to find whether they are equal, greater than or...

Close