Java ProgrammingLearn Decision Making in Java Programming Language

Learn Decision Making in Java Programming Language

 

In your daily life, you have to make decisions all day long. You are often faced with two or more options, if you choose the first there shall be a consequence, if you choose the other there shall be another consequence. The situation is no different in Java. Imagine that you are coding an application for weather forecast. Your code reads the current temperature from some source, and displays an appropriate message to the user based on the reading. So if it is more than 30°C, the message says “It’s  hot”, if it is between 20°C and 29°C, the message says “It’s mild”. Finally, if it is less than 20°C, the message is “It’s cold”. For this and other similar examples, we must use the if condition.

If-else statements

Let’s code this weather application thing first:

public class Conditionals {
	public static void main(String[] args) {
		int current_temp = 25;
		if (current_temp > 30) {
			System.out.println("It's hot");
		} else {
			System.out.println("It's mild");
		}
	}
}

The code simply declares a variable current_temp of type integer, and sets its value to 25. Then comes the if condition statement. It starts with if followed by the condition between parentheses. The condition is any statement that outputs a Boolean value: true or false. In our case, the test is whether or not the current_temp variable is more than 30. The body of if statements is placed between curly braces. If you have only one statement in the body, you can get rid of the curly braces, however, this is not recommended.

An if statement may or may not have an else part. But more often than not, you’ll need one. Else is invoked when the if condition returns false. So in our case, whenever the temperature is more than 30°C, “It’s hot” will be displayed.

But what if you want to check for multiple conditions? In our example, we had 3 different conditions to check for. In such a case, you can use else-if. Observe the following modification in our example:

public class Conditionals {

    public static void main(String[] args) {
        int current_temp = 25;
        if (current_temp > 30){
            System.out.println("It's hot");
        } 
        else if (current_temp >= 20 && current_temp < 30){
            System.out.println("It's mild");
        }
        else {
            System.out.println("It's cold");
        }
    }
}

Adding else if to the conditional statements provides us with the missing part. If the temperature is between 20 and 30 degrees, display “It’s mild”. Otherwise, display “It’s cold”. You can add as many else if statements as required. Notice the use of &&, which stands for AND in Java.

Java Programming Course for Beginner From Scratch

The switch statement

In our weather example, we were considering ranges of temperatures. But what if you want to work with discrete values? For example, you are developing an application that will automate car driving. You want the application to read the traffic light and act accordingly. So when the lights are read, the car should stop, when they are yellow the car should slow down, and when they are red, the car should stop completely. One option is to use if, else if and, else statements. This may be fine for an application that works with only 3 possible options. But if you are working with more, things are going to get difficult to manage. This is where the switch statement fits in. Have a look at the following:

public class Conditionals {

    public static void main(String[] args) {
        String light = "yellow";
        switch (light){
            case "red":
                System.out.println("Stopping the car");
                break;
            case "yellow":
                System.out.println("Slowing down the car");
                break;
            default:
                System.out.println("Moving the car");
        }
    }
}

The switch statement consists of the following components:

  1. The value to test, between brackets (light in our case).
  2. The case keyword followed by the value you want to test for (red, yellow, or green).
  3. The code that will get executed when the value is matched.
  4. An optional break keyword. The break keyword forces code execution to quit the switch block once the value is matched. In other words, if you want to execute the same code on multiple case conditions, use code like the following:
switch (light){
            case "red":
            case "yellow":
                System.out.println("Slowing down the car");
                break;
            default:
                System.out.println("Moving the car");
        }

This will let you “Slow down the car” when the lights go either red or yellow.

  1. Here you write the default code that will be executed if none of the case conditions are matched.

Conclusion

In this article, we have discussed decision making using if statements and switch case.

  • An if statement executes its body if a specific condition is met.
  • An if statement may have an else part that is executed if the condition is not met.
  • Optionally, one or more else if parts could be used as alternative(s) if the first condition is not met.
  • The switch case structure is useful when one variable is to be checked against a set of values.

In the next article, we will talk about Loops: an interesting topic that you shouldn’t miss. So, stay here.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -