Before we dive into studying decision statements, we’d like to remind you to check out the previous post here. Pay special attention to comparison operators and logical operators. These operators will be the foundation for brainstorming and creating the most effective and precise decision statements. In practical use, decision statements are something programmers work with in almost every project, and it’s simply unimaginable to create any serious program without them. But what we want to emphasize is that your ability to construct a flawless decision statement in programming will determine not only the flow of your program but also the entire program itself.
What you’ve learned so far is how computers think, but with decision statements, you begin to think about how your program will function. If you’re a beginner and starting with simple, small programs, you’ll often create common and straightforward statements that are self-explanatory, and there’s not much to overthink in those cases. However, when you need to construct statements based on complex and challenging decisions, that’s where your programming thinking ability comes into play, and you’ll definitely make a lot of mistakes until you bring your programming experience to perfection. So don’t take decision statements lightly and just breeze through them. Instead, brainstorm a bit to solve some of your personal problems in a programming way.
Decision statements are just one category of control statements. Control statements are divided into conditional statements, loops, and jumps. Decision statements are conditional statements. Other categories include loops, which are iterations, and jumps, which are commands that help you exit loops and functions. You’ll learn about those later in upcoming posts. For now, we’ll focus only on decision statements. The Java programming language supports two types of decision statements: if-else and switch-case. The if-else statement is used when you have fewer conditions, while the switch-case is used when you have more conditions. Thanks to these statements, you control the program’s execution based on conditions known at runtime. Your capabilities and flexibility with these are vast, considering you can even nest one condition within another or multiple others. This is called branching. But let’s take it step by step and ease your learning process with practical use.
How If-Else Statements Work in Java Programming Language?
The if-else statement is a conditional branching statement that allows the program's flow to be directed along one or more paths. Simply put, decision statements are based on conditions that determine how the program will proceed. The general structure of an if-else statement can take three forms and looks like this:
- The simplest form: if the condition is true, execute the code in the block; if not, skip the entire if statement.
if (condition) {
execute this block of code;
}
- If-else form: if the condition is true, execute the code in the block, but if it isn’t, execute the code in the else block.
if (condition) {
execute this block of code;
} else {
execute this block of code;
}
- If-else-if form: if the condition is true, execute the code in the block, but if not, try the second condition in the else-if block. If that condition isn’t true either, try the next one, and so on, depending on how many else-if blocks there are; but if there are no more else-if blocks, execute the code in the else block.
if (condition) {
execute this block of code;
} else if (condition) {
execute this block of code;
} else {
execute this block of code;
}
Note that in the third form of the if-else statement, you can have multiple conditions, i.e., multiple else-if blocks. Regarding the conditions, what you type within the parentheses, no matter how complex your conditions are, they ultimately boil down to a boolean value, either true or false. This means if the condition is true, the block of code will be executed; if it’s false, the block of code will not be executed. For example, if the user's input is a number, perform addition; if it’s not, skip it. Otherwise, an error will occur because you can't add numbers and letters. To make this clearer, let’s move on to the practical part. Start a new program, name it ifelse, and type the following code.
package com.tutorial;
import java.util.Scanner;
public class ifelse {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a character:
");
char c = scan.next().charAt(0);
if(Character.isUpperCase(c)) {
System.out.println("The character is an
uppercase letter.");
}
else if(Character.isLowerCase(c)) {
System.out.println("The character is a
lowercase letter.");
}
else if(Character.isDigit(c)) {
System.out.println("The character is a
digit letter");
}
else {
System.out.println("The character is not
alphanumeric.");
}
}
}
As you can see in the code; the user is expected to enter one character from the keyboard. We don't know what he will bring. Maybe he wants to enter a number, but by mistake he types a letter or some special character. In order to prevent us from making mistakes in our program, we use in this case the third form of the if else decision statement. If the user enters a letter, we will print in the terminal that he typed the letter. In a more serious program, instead of such printouts, we would inform the user that he made a mistake and again offer him the opportunity to re-enter the character, or we would even constantly ask him to enter the character until he types a number if we need a number from him. And if he did that, only then would our program be executed further. As you can see, you decide with the help of the if-else statement how the program will be executed. When we execute this program depending on user input, the result will be similar to.
Enter a character:
m
The character is a
lowercase letter.
Process finished
with exit code 0
You can see how the previous program was created and how it is executed in the following video.
Understanding Switch-Case Logic in the Java Programming Language
In the previous program, we saw how decision statements are used when you have one, two, or more conditions. But what do you do when you really have more conditions, such as 7 for the days of the week or 12 for the months of the year? You could use an if-else decision statement with many else-if blocks, but there's a simpler way to handle this using switch-case statements, which will also make your program execute a bit faster. With a switch-case statement, you can easily direct the flow of your program to a specific block of code based on the value of an expression. The general structure of a switch-case statement looks like this:
switch (value) {
case 1:
execute this block of code if the value is 1;
break;
case 2:
execute this block of code if the value is 2;
break;
default:
execute this block of code if the value does not match any condition;
break;
}
As you can see, the switch-case statement is straightforward when dealing with multiple conditions. Of course, the case blocks do not have to be numbers; they can also be letters or logical conditions. If a case block has a value that matches the value being tested, the code in that block will be executed. The default block in a switch-case statement is similar to the else block in an if-else statement. Keep in mind that your switch-case statement does not need to have a default block, but it is recommended to include one. Start a new program and name it switch. Enter the following code.
package com.tutorial;
import java.util.Scanner;
public class switchcase {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer from 1 to 7: ");
int day = scan.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("Your input is not an integer from 1 to 7! ");
break;
}
}
}
As you can see in the previous code, the user is asked to enter an integer from 1 to 7. The program should examine as many as 7 conditions and based on them display what day of the week it is in English. This program is adapted to our area, so the first day of the week is Monday, otherwise for the American area, the first day of the week is Sunday. When the user enters a number from 1 to 7; the switch-case statement will do its job more simply than if you wrote as many as 6 else if blocks in the if else decision statement. And of course, here we use the default block if the user types in a higher or lower number than requested. When we run the program, the result will depend on the user's input.
Enter an integer
from 1 to 7:
3
Wednesday
Process finished
with exit code 0
You can see how the previous program was created and how it is executed in the following video.
How to Create a Simple Monthly Calendar in Java Programming Language?
Now you're wondering what this is; what does the monthly calendar have to do with statements and decisions. Well, we decided that since you are good, we will reward you with another small program. But in this case, you have some parts of code in the program that you haven't learned yet, but you will learn them in one of the next posts like arrays. Again, that shouldn't stop you from stepping into code you don't understand. In real jobs, you will often encounter code and things you've never even seen. That should not be an obstacle for you. Type this code in full, but pay attention to the professional use of complicated if else statements for decision making. Name the program monthcalendar.
package com.tutorial.monthcalendar;
import java.util.*;
public class monthcalendar {
public static void main(String[] args) {
int year;
int spaces;
int month;
Scanner scan = new Scanner(System.in);
// Prompts user to enter year
System.out.println("Enter a year: ");
year = scan.nextInt();
// Prompts user to enter month
System.out.println("Enter a month: ");
month = scan.nextInt();
scan.close();
// Calculation the first day of that month
Calendar cal = Calendar.getInstance();
cal.set(year, month - 1, 1);
int day = cal.get(Calendar.DAY_OF_WEEK) - 1;
// The name of month
String[] months = {
"", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
// The number of day in month
int []days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// Check for a leap year
if((((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) && month == 2)
days[month] = 29;
// Print the calendar header
// Display months and a year
System.out.println(" " + months[month] + " " + year);
// Display the lines
System.out.println("_____________________________________________");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
// Space required
spaces = day;
// Print the calendar
for (int i = 0; i < spaces; i++)
System.out.print(" ");
for (int i = 1; i <= days[month]; i++) {
System.out.printf(" %4d ", i);
if (((i + spaces) % 7 == 0) || (i == days[month])) System.out.println();
}
System.out.println();
}
}
Look at the preceding code and try to figure out for yourself how the program flow is executed. When you start the execution of this program, you will get the result depending on your data input.
Enter a year:
2024
Enter a month:
9
September 2024
_____________________________________________
Sun
Mon Tue Wed
Thu Fri Sat
1
2 3 4
5 6 7
8
9 10 11
12 13 14
15
16 17 18
19 20 21
22
23 24 25
26 27 28
29
30
Process finished
with exit code 0
You can see how the previous program was created and how it is executed in the following video.
No comments:
Post a Comment