The Wayback Machine - https://web.archive.org/web/20240910094020/https://www.geeksforgeeks.org/java-if-else-if-ladder-with-examples/
Open In App

Java if-else-if ladder with Examples

Last Updated : 20 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Decision Making in Java helps to write decision-driven statements and execute a particular set of code based on certain conditions.
Java if-else-if ladder is used to decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

Syntax:  

if (condition)
    statement 1;
else if (condition)
    statement 2;
.
.
else
    statement;

Working of the if-else-if ladder:  

  1. Control falls into the if block.
  2. The flow jumps to Condition 1.
  3. Condition is tested. 
    1. If Condition yields true, goto Step 4.
    2. If Condition yields false, goto Step 5.
  4. The present block is executed. Goto Step 7.
  5. The flow jumps to Condition 2. 
    1. If Condition yields true, goto step 4.
    2. If Condition yields false, goto Step 6.
  6. The flow jumps to Condition 3. 
    1. If Condition yields true, goto step 4.
    2. If Condition yields false, execute else block. 
      Goto Step 7.
  7. Exit the if-else-if ladder.

Flowchart if-else-if ladder: 

Example 1:
 

Java




// Java program to illustrate if-else-if ladder
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        // initializing expression
        int i = 20;
 
        // condition 1
        if (i == 10)
            System.out.println("i is 10\n");
 
        // condition 2
        else if (i == 15)
            System.out.println("i is 15\n");
 
        // condition 3
        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

Outside if-else-if

 

Time Complexity: O(1)

Auxiliary Space: O(1)

Dry running 

Example 1: 

1. Program starts.
2. i is initialized to 20.
3. condition 1 is checked. 20 == 10, yields false.
4. condition 2 is checked. 20 == 15, yields false.
5. condition 3 is checked. 20 == 20, yields true.
  5.a) "i is 20" gets printed.
6. "Outside if-else-if" gets printed.
7. Program ends.

Example 2:  

Java




// Java program to illustrate if-else-if ladder
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
 
        // initializing expression
        int i = 20;
 
        // condition 1
        if (i < 10)
            System.out.println("i is less than 10\n");
 
        // condition 2
        else if (i < 15)
            System.out.println("i is less than 15\n");
 
        // condition 3
        else if (i < 20)
            System.out.println("i is less than 20\n");
 
        else
            System.out.println("i is greater than "
                               + "or equal to 20\n");
 
        System.out.println("Outside if-else-if");
    }
}


Output: 

i is greater than or equal to 20

Outside if-else-if

 

Time Complexity: O(1)

Auxiliary Space: O(1)

Related Articles: 
 

  1. Decision-Making in Java
  2. Java if statement with Examples
  3. Java if-else statement with Examples
  4. Switch Statement in Java
  5. Break statement in Java
  6. return keyword in Java


Previous Article
Next Article

Similar Reads

Naveed Ahmed Janvekar – Geek on the top | "Success is like a ladder and no one has ever climbed a ladder with their hands in their pockets"
Geek on the top is all about success stories of Geeks who are working hard to chase their goals and are the inspiration for other geeks.Today we have brought to you the story of Naveed Ahmed Janvekar who is currently working as a Senior Data Scientist at Amazon at one of the world's leading technology companies - Amazon. He leads the abuse preventi
6 min read
Program to print the Ladder Pattern
Given an integer N, the task is to print the ladder with N steps using '*'. The ladder will be with the gap of 3 spaces between two side rails. Input: N = 3 Output: * * * * ***** * * * * ***** * * * * ***** * * * * Input: N = 4 Output: * * * * ***** * * * * ***** * * * * ***** * * * * ***** * * * * Approach: Dividing the pattern into two sub-patter
4 min read
Decision Making in Java (if, if-else, switch, break, continue, jump)
Decision Making in programming is similar to decision-making in real life. In programming also face some situations where we want a certain block of code to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. These are used to cause t
7 min read
Java if-else
Decision-making in Java helps to write decision-driven statements and execute a particular set of code based on certain conditions. The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. In this article, we will learn about Java if-else. If-Else in JavaIf- else toget
3 min read
Writing clean if else statements
Using if else chaining some time looks more complex, this can be avoided by writing the code in small blocks. Use of conditional statement increases the code readability and much more. One best practice should be handling error case first. Below shown example shows how to handle error cases and simplify the if else logic.Examples 1: updateCache()-
5 min read
switch vs if else
Prerequisite - Switch Statement, Decision making(if else) A switch statement is usually more efficient than a set of nested ifs. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. Check the Testing Expression: An if-then-else statement can test expressions
3 min read
Output of C programs | Set 65 (If-Else)
Prerequisite : Decision making in CQuestion 1 C/C++ Code #include&quot;stdio.h&quot; #include&quot;stdlib.h&quot; void reverse(int i) { if (i &gt; 5) exit(0); printf(&quot;%d\n&quot;, i); return reverse(i++); } int main() { reverse(1); } OPTIONS: a)Segmentation fault b)Compilation error c)Print 1 Infinite time d)Both a &amp; c OUTPUT: (d)Both a
2 min read
Rachit Jain - Geek on the top | "Stop starting, start finishing: Don't just give up on things and then start doing something else"
Geek on the top is all about success stories of Geeks who are working hard to chase their goals and are the inspiration for other geeks.   Rachit Jain is an IIT Roorkee Alumnus and a Software Engineer at Microsoft. Rachit has his programming Youtube channel named "Algorithms With Rachit Jain". He believes that his YouTube channel empowers other stu
7 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
Java lang.Long.builtcount() method in Java with Examples
java.lang.Long.bitCount() is a built in function in Java that returns the number of set bits in a binary representation of a number. It accepts a single mandatory parameter number whose number of set bits is returned. Syntax: public static long bitCount(long num) Parameters: num - the number passed Returns: the number of set bits in the binary repr
3 min read
Java Clock tickMinutes() method in Java with Examples
java.time.Clock.tickMinutes(ZoneId zone) method is a static method of Clock class that returns the current instant ticking in whole minutes using the best available system clock and the time-zone of that instant is same as the time-zone passed as a parameter. Nanosecond and second fields of the clock are set to zero to round the instant in the whol
3 min read
Java Clock withZone() method in Java with Examples
The java.time.Clock.withZone(ZoneId zone) method is a method of Clock class which returns a clock copy of clock object on which this method is applied, with a different time-zone. If there is a clock and it is required to change the zone of clock but not other properties, then withZone() method is used. This method takes zone as parameter which is
3 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java 8 | IntToDoubleFunction Interface in Java with Examples
The IntToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and gives a double-valued result. The lambda expression assigned to an object of IntToDoubleFunction type is used to define
1 min read
Java 8 | DoubleToLongFunction Interface in Java with Examples
The DoubleToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an long-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to defi
1 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Java.lang.Short toString() method in Java with Examples
toString(short) The static toString() method of java.lang.Short returns a new String object representing the specified short. The radix is assumed to be 10.This is a static method hence no object of Short class is required for calling this method. Syntax: public static String toString(short b) Parameters: This method accepts a parameter b which is
2 min read
Java.util.function.BiPredicate interface in Java with Examples
The BiPredicate&lt;T, V&gt; interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on two objects and returns a predicate value based on that condition. It is a functional interface and thus can be used in lambda expression also. public interface BiPredicate&lt;T, V&gt; Methods: test(): This functio
2 min read
Java.util.function.DoublePredicate interface in Java with Examples
The DoublePredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a Double object and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface DoublePredicate Methods test(): This function evaluates a co
2 min read
Java.util.function.LongPredicate interface in Java with Examples
The LongPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a long value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface LongPredicate Methods test(): This function evaluates a condition
2 min read
Java.util.function.IntPredicate interface in Java with Examples
The IntPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on an integer value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface IntPredicate Methods: test(): This function evaluates a condit
2 min read
Java IO : Input-output in Java with Examples
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations. Before exploring various input and output streams lets look at 3 standard or default streams that Java has to provide
7 min read
Practice Tags :