Java Tutorials – If-Else Switch and Loops in Java

Hello people…! This is a new post in Java Tutorials – If-Else Switch and Loops in Java. In this post, I will talk about branching and looping in Java, i.e. , about the if-else, switch and loop constructs. With this you can write plenty of programs in Java which you wrote to  practice C language. Although the branching and looping in Java is very much like the C language, Java comes with a bunch of new features which C doesn’t have. So… Let’s get started…!

The If-Else Syntax

import java.util.Scanner;

public class IfElse {

    public static void main(String[] args) {
        int Bob, Andy, Birch;
        Scanner scan = new Scanner(System.in);

        System.out.println("Enter Bob's height -");
        Bob = scan.nextInt();
        System.out.println("Enter Andy's height -");
        Andy = scan.nextInt();
        System.out.println("Enter Birch's height -");
        Birch = scan.nextInt();

        // Simple If construct
        if (Bob > 6) {
            System.out.println("Bob is over six feet..!");
        }

        // If-else construct
        if (Bob > Andy) {
            System.out.println("Bob is taller than Andy!");
        } else {
            System.out.println("Andy is taller than Bob!");
        }

        // Nested If-else construct
        if (Bob > Andy) {
            if (Bob > Birch) {
               System.out.println("Bob is the tallest!");
            } else {
               System.out.println("Birch is the tallest!");
            }
        } else {
            if (Andy > Birch) {
               System.out.println("Andy is the tallest!");
            } else {
               System.out.println("Birch is the tallest!");
            }
        }

        // Else-If ladder construct
        if (Bob >= 7) {
            System.out.println("Bob is very very tall!");
        } else if (Bob >= 6) {
            System.out.println("Bob is very tall!");
        } else if (Bob >= 5) {
            System.out.println("Bob is pretty tall!");
        } else if (Bob >= 4) {
            System.out.println("Bob is a kid!");
        } else {
            System.out.println("Bob is a lilliput!");
        }
    }

}

This is a program which takes the heights of three friends from the user and displays some statistics. The various types of if-else branching constructs have been demonstrated. This is exactly as in C.

Switch in Java

The syntax of the switch statement in Java is exactly as in C. switch in Java too, has the “cascading problem” that occurs when you don’t break from the switch. But switch in Java comes with an additional feature that its supports Strings too. So, in Java, using a switch, we can compare Strings. Below, is a small program which computes the trip charges for a vacation company. The user gives the name of the destination as input, which is compared with available destinations using the switch statement.

import java.util.Scanner;

public class JoyRides {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int distance, persons;
        double cost;

        System.out.println("Welcome to Joy Rides..!");
        System.out.print("Select a destination - ");
        System.out.print("Chicago / ");
        System.out.print("Witchita / ");
        System.out.print("New York / ");
        System.out.println("Washington");

        String destination = scan.nextLine();

        switch (destination) {
            case "Chicago" :
                distance = 100;
                break;
            case "Witchita" :
                distance = 200;
                break;
            case "New York" :
                distance = 300;
                break;
            case "Washington" :
                distance = 400;
                break;
            default:
                System.out.println("Invalid Destination!");
                return;
        }

        System.out.println("For how many persons?");
        persons = scan.nextInt();

        switch (persons) {
            case 1 :
                cost = 150;
                break;
            case 2 :
                cost = 400;
                break;
            case 3 :
                cost = 750;
                break;
            case 4 :
                cost = 1200;
                break;
            default:
                System.out.println("Too many!");
                return;
        }

        cost = cost + distance * 12.5;

        System.out.println("Total cost of travel is = "
                + cost);
    }

}

for loop in Java

The syntax of the for loop in Java is exactly as in C. Unlike in C, we can declare the counter inside the loop statement itself to tighten the scope of the variable, which is a good thing. Below, is a simple program which prints the contents of an array of strings and its length.

public class ForLoop {

    public static void main(String[] args) {
        String[] countries = {
                                "India",
                                "United States of America",
                                "Australia",
                                "Germany",
                                "Spain",
                                "Portugal"
                            };

        for (int i = 0; i < countries.length; ++i) {
            System.out.println(countries[i] + "-"
                    + countries[i].length());
        }
    }

}

As you can see, I was able to declare the counter of the loop i in the for statement itself. I used a couple of new things –

  • countries.length
  • countries[i].length()

First, is a feature of Java to know the length of arrays and the second, is a method to know the length of the String. We will have a detailed discussion about them later.
In the for loop, the we can initialise more than one variable. The statements are to be separated by a comma. A sample would be –

for (int i = 0, j = 0; i < 10 && j < 20; ++i) {
    // code
}

Similarly, the increment / decrement region can also have multiple statements separated by a comma –

for (int i = 0, j = 0; i < 10 && j < 20; ++i, ++j) {
    // code
}

Enhanced for loop in Java

There is another syntax for writing the for loop in Java. In this, we iterate through every element in a given Collection, like arrays. Unlike in the normal for loop, here, we won’t have an option of skipping an item, we must traverse though every item. The syntax is as –

for(DataType variable : Collection) {
    // code
}

Where the Collection is an array for now. Later, we’ll see what else we can put there. The data type of the variable must match the data type of the Collection. So, we can re-write the ForLoop Class using the enhanced for loop –

public class EnhancedForLoop {

    public static void main(String[] args) {
        String[] countries = {
            "India",
            "United States of America",
            "Australia",
            "Germany",
            "Spain",
            "Portugal"
        };

        for (String name : countries) {
            System.out.println(name + "-" + name.length());
        }
    }

}

This is the enhanced for loop in Java. It is a more compact way of writing the for loop. For each iteration, the variable “name” will contain the value of that corresponding iterate item from the countries[] array, or, the vaguely speaking, value of countries[i]. One more important thing about this feature is that, the enhanced for loop is read-only. That is, using the enhanced for loop, we cannot modify the elements of the existing array.

while loop in Java

The while loop in Java has the exact syntax of the while loop in C. But, a matter of notice is that, Java is a strongly typed language. So, the condition in the while statement must yield a boolean value. We have a common practice of writing while loops in C as –

int i = 10;

while (i--) {
    // code
}

This will NOT work in Java. Because we are giving an integer in the condition. In C, non-zero values are treated to be true and zero is treated as false. There is no such thing in Java. If we write the while loop in that way, there will be a compilation error saying, “Incompatible Types : int cannot be converted to boolean”. I am emphasizing on this because I faced this many times, so I want you to keep this in the back of your mind. If not for this, the while loop in Java is exactly as in C. Just for practise, try re-writing the above countries program using a while loop. It should look like this –

public class WhileLoop {

    public static void main(String[] args) {
        String[] countries = {
            "India",
            "United States of America",
            "Australia",
            "Germany",
            "Spain",
            "Portugal"
        };

        int i = 0;

        while (i < countries.length) {
            System.out.println(countries[i]
                + " - " + countries[i].length());
            ++i;
        }
    }

}

do while loop in Java

The do while loop in Java is also exactly as in C. The same point about the boolean expression holds here too. To make things clear, let’s re-write the same countries code with a do while loop –

public class DoWhileLoop {

    public static void main(String[] args) {
        String[] countries = {
            "India",
            "United States of America",
            "Australia",
            "Germany",
            "Spain",
            "Portugal"
        };

        int i = 0;

        do {
            System.out.println(countries[i]
                    + " - " + countries[i].length());
            ++i;
        } while (i < countries.length);
    }

}

This is the do while loop in Java. I might as well have written just the loop part of it for each of the types of loops. But I took the pain of writing the whole program so that you get used to the class and public static void main(String[] args) stuff. As insignificant as it may seem to you, I still insist you to write all the programs again yourself. You cannot learn a language or be comfortable with it without writing code, even if you already know the most part of it.

Labelled Loops in Java

This is a feature of Java where we can assign some labels, or names, to the loops. This is not there in C, so you’d better watch closely..! Let’s take a small example to understand the syntax –

OuterLoop:
for (int i = 0; i < 10; ++i) {

    InnerLoop:
    for (int j = 0; j < 10; ++j) {
        // code
    }

}

Here, the names InnerLoop and OuterLoop are the labels of the respective loops. So, to assign a label to a loop, we write the label followed by a colon, just before the loop statement. But, why would anyone bother about this..? These become handy when used with break and continue clauses. Using only a break or continue clause would would affect the execution of the loop which is the nearest loop outside, or parent loop, as it is in C. But using the labels, we can break or continue from any loop…!

public class LabelledLoops {

    public static void main(String[] args) {
        int[][] array = {
                            {1, 2, 3},
                            {4, 5, 6},
                            {7, 8, 9}
                        };

        int findNumber = 5, i, j = 0;

        OuterLoop:
        for (i = 0; i < array.length; ++i) {
            InnerLoop:
            for (j = 0; j < array[i].length; ++j) {
                if (array[i][j] == findNumber) {
                    break OuterLoop;
                }
            }
        }

        System.out.println("Found at array[" + i + "][" + j + "]");
    }

}

This is how we use the labelled loops. That program, searches for an element in a 2D array linearly, and breaks out of both the loops when it finds the element. We can give labels not only to for loops, but also to while and do while loops and even blocks (code inside “{..}”) if it seems sensible to you.

Summary

  • The switch construct in Java supports Strings also. Hence, we can take decisions based on string-matching.
  • Just like the switch in C, the case statements cascade if break is not given.
  • The conditions in the while loop construct strictly expects a boolean value. So it is for the do while loop.
  • We can use labels with loops which can be used to break or continue from a not-the-nearest loop.

Practice

  • How many times will the “InfiniteLoop” loop run…?
    public static void main(String[] args) {
        short i;
    
        InfiniteLoop:
        for (i = 1; i > 0; ++i) {
            System.out.println(i);
        }
    }
    
  • Can you guess the output of this program..?
    public static void main(String[] args) {
        byte i, j;
    
        OuterLoop:
        for (i = 1; i <= 10; ++i) {
    
            InnerLoop:
            for (j = 1; j <= 10; ++j) {
                System.out.print("* ");
    
                if (j == i) {
                    System.out.println();
                    continue OuterLoop;
                }
            }
    
            System.out.println("The end..!");
        }
    }
    

    P.S. – Don’t run it..! Try it manually..! 😛

  • Can you guess the output of this program..?
    public static void main(String[] args) {
        byte i, j;
    
        for (i = 1, j = 10; i <= 10 && j >= 1 && j >= i;) {
            if (i == j) {
                System.out.println("*");
                ++i;
                j = 10;
            } else {
                System.out.print("* ");
                --j;
            }
        }
    }
    

    P.S. – Don’t run it..! Try it manually..! 😛

I hope you have understood the differences of the features provided by Java and C when it comes to branching and looping. Feel free to comment your doubts..! Keep practising..! Happy Coding..! 😀

Leave a Reply

Your email address will not be published. Required fields are marked *