Conditionals in Java is a must know if you want to write code in Java that solves a problem. It is one of the most important building blocks in every programming language.
In this article you will learn what are conditionals statements and how to use them.
Commonly, in our life we take a decision according to a certain condition. Let’s examine some examples:
- I’ll go to play soccer if it does not rain.
- I can learn if I study.
- If I have enough money I’ll take a taxi to school, otherwise I’ll walk.
- If I have enough money by the end of the year, then I can go for holidays, otherwise I’ll stay at home.
- If I get 1000 $, then I’ll buy a plane ticket to my favorite place. If I get only 500 $, then I’ll buy a train ticket to my favorite. Otherwise, I won’t go anywhere.
You might identify with some of the situations above, but if not, I’m sure you can write one that happened to you.
As you must remember, we use programming languages to model real-life situations. This one is one of them. Let’s see how to model this type of situations in Java.
Conditionals in Java: If-then-else
As you can see from the previous examples, there is a common structure in this type of situation. If some condition is meet, then I’ll do something. Otherwise, I’ll do something else.
In Java (and in many other programming languages), we use the structure if-then-else.
if (condition) then {
//instructions
}
else {
//instructions
}
The condition must return a boolean value. Examples of valid conditions:
- number1 > number2
- a % 2 == 0 && a > 5
- a + 5 > b
We basically have to use operators to create the conditions according to the problem we want to solve.
In some cases, you will have more than conditions, like in the last example from the previous section. In that case, after the “else” you can add a new condition. For instance:
If (I get 1000 $) then {
I’ll buy a plane ticket to my favorite place.
}
else if (I get only 500 $) then {
I’ll buy a train ticket to my favorite.
}
else {
I won’t go anywhere.
}
You can add as many extra “else if (condition)” as you need. Also, the last part of the conditional statement (else) is not compulsory.
Java example
Problem: create a console application in Java that receives an integer number from the keyboard and prints whether the number is odd or even.
By definition, an even number is a number that can be expressed as the double of another number (a is even if a=2*t, from some integer t). The previous definition can be translated, for our benefit, into this: a number is even if the remainder of the division of that number by 2 is 0. We know that we have available an operator in Java (%) that returns the reminder of the division.
Our console application will be as follows.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Here we create the object scanner
//(notice that is different from the type Scanner)
Scanner scanner = new Scanner(System.in);
// now we read an integer from hte keyboard with the object that was created
int number = scanner.nextInt();
if (number % 2 == 0){
System.out.println("The number is even");
}
else{
System.out.println("The number is odd");
}
}
}
Conditionals in Java: Switch-case
There is another type of statement that we can use to model conditional situations: switch-case.
“Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).” Source.
The previous text is from the official Java documentation. It means that there are some restrictions in the way we can use it, but it is definitely helpful in some situations.
The general structure is as follows:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The restriction is basically in what we can use as expression.
Let’s see one of the common examples you can find in the literature.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Here we create the object scanner
//(notice that is different from the type Scanner)
Scanner scanner = new Scanner(System.in);
// now we read an integer from hte keyboard with the object that was created
int day = scanner.nextInt();
switch (day){
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break;
default: System.out.println("Unknown day");
}
}
}
Summary
In this article, you learned an important structure that you can find in most programming languages: conditionals.
Conditionals are useful in many situations. The same way we are presented in our life with certain conditionals events, you will have to do it when using a programming language.
You can use two types of conditional statements: if-then-else or switch-case. Which one to use? Here is another conditional event. It will depend on the type of condition and in other cases, it depends on you. In some cases, you can use any of the two and obtain the same result.
The latest, is an important affirmation you must remember. In programming, there are several ways to solve the same problem.
H@ppy coding!