Java Tutorial #4 – Control Statements

if Statement, if-else Statement, Nested if Statement, Switch Statement

Table of Contents

Introduction

Control statements are used to change the flow of execution based on changes to certain variables in the code. One of the types of control statements are the selection statements or decision statements. These should be used when you want to check some condition and take a decision based on the condition. Java supports the if and switch statement decision statements

The ‘If’ Statement

The if statement is the most widely used control statement. It is used to check a condition. If the condition is true, it executes some code. You can also have an optional else part that executes if the condition is false. An if statement has the following syntax:

Syntax

if(condition){
  //some code here
}
else { // this part is optional
    //some code here
}

So, the if keyword is followed by a condition that evaluates to a boolean value. If the boolean value is true, the code within the if block is executed. If the boolean value is false, the code within the else block is executed. The else block is optional.

Basic If Statement

The if statement can be used by itself, without having an else statement. In such a scenario, if the condition specified within the if statement is true, the code within the if block is executed after which control transfers outside the if block. If the condition in the if statement is false, the if block is not entered and control directly transfers outside the if block. The following code demonstrates this:

System.out.println("Enter a Value:");
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
if(i > 5) {
System.out.println("Value is greater than 5");
}
System.out.println("Outside if");
scanner.close();

Here, the if statement checks if the value entered by the user is greater than 5. If so, it executes a Sysout statement.  If the value entered by the user is less than 5, the if block is not entered. So, if the user enters the value 10, this code prints the following output:

Enter a Value:
10
Value is greater than 5
Outside if
If the user enters the value 2, this code prints the following output:
Enter a Value:
2
Outside if

If-else Statement

The else statement can also be used with the if statement. If the condition within the if statement is false, the code within the else block gets executed. The following code demonstrates this:

System.out.println("Enter a Value:");
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
if(i > 5) {
System.out.println("Value is greater than 5");
}
else {
	System.out.println("Value is less than 5");
}
scanner.close();

Here, the if statement checks if the value entered by the user is greater than 5. If so, it executes a Sysout statement, otherwise, it executes a different Sysout statement. So, if the user enters the value 10, this code prints the following output:

Enter a Value:
10
Value is greater than 5
If the user enters the value 2, this code prints the following output:
Enter a Value:
2
Value is less than 5

Nested If Statement

A nested if is simply an if statement within another if statement. Only if the outer if statement is true, the condition within the inner if statement is checked. Each if statement can have an optional else statement. The following code demonstrates this:

System.out.println("Enter a Value:");
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
if(i >= 5) {
if(i < 10) {
		System.out.println("Value is between 5 to 10");
	}
}
else {
	System.out.println("Value is less than 5");
}
scanner.close();

Here, the if statement checks if the value entered by the user is greater than or equal to 5. If so, there is another if statement within this if statement that checks if the value is less than 10. The inner if does not have an else statement while the outer if has an else statement. So, if the user enters the value 6, this code prints the following output:

Enter a Value:
6
Value is between 5 to 10
If the user enters the value 2, this code prints the following output:
Enter a Value:
2
Value is less than 5

The Switch Statement

Sometimes, you will need to write code that checks for several conditions. In such a scenario using multiple if-else statements makes the code difficult to read. Java provides the switch statement as an alternative. It checks a value and executes one of several code blocks based on the value. A switch statement has the following syntax:

Syntax

switch(expression) {
		case value1: 
			//some code
			break; //optional
		case value2: 
			//some code
			break; //optional
		…..
case valuen: 
			//some code
			break; //optional

		default: 
			//some code
			break; //optional
		}
	}

The switch keyword is followed by an expression. This expression is compared with the value specified with every case statement. As soon as a match is found, the code following that case statement is executed. If there is a break statement in the case statement, no further case statements are checked and control transfers outside the switch statement. In case the expression does not match any case statement, the code following the default keyword is executed.

Example

The following code demonstrates a basic switch block:

System.out.println("Enter a Value:");
Scanner scanner = new Scanner(System.in);
int month = scanner.nextInt();
switch(month) {
case 1: 
	System.out.println("January");
	break;
case 2: 
	System.out.println("February");
	break;
case 3: 
	System.out.println("March");
	break;
//code for other months here
default: 
	System.out.println("Invalid month");
	break;
}
scanner.close();
Enter a Value:
2
February
If the user enters a value greater than 12, this code prints the following output:
Enter a Value:
14
Invalid month

Conclusion

Java decision statements help to execute code based on some conditions. Java has two main decision statements, if and switch. The if statement can have an optional else part. The switch statement can be used when you want to check for multiple values.

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

JAVA TUTORIALS

Recent Posts

RELATED POSTS

Java DecimalFormat Class

When you need to format decimal numbers, such as taking three or two decimal places for a number, showing only the integer part of...

Convert String to Date Using SimpleDateFormat Class

Sometimes, you may need to convert a String to a java.util.Date object. For this, you need to use the SimpleDateFormat class. You need to...

Format Decimal Numbers Using Pattern

The java.text.DecimalFormat class is used to format numbers using a user specified formatting. This concrete subclass of NumberFormat, allows formatting decimal numbers via predefined...

How To Create Singleton Class in Java

Design patterns Overview Design patterns are basically solutions to programming problems that developers normally encounter during software development. Design patterns were first documented by four...

Â

CHECKOUT 'HOW-TOs'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string...

MORE ON CODEX

MORE IN THIS CATEGORY

Maven Build Life Cycles, Phases and Goals

Maven’s Sequential Execution In Maven, you have the option of executing a build phase or build goal. But unlike build goals, which can be called...

Convert String to java.time.LocalDate without Formatter

The LocalDate class has a parse method. You can use this to convert a String to a LocalDate. So, this code simply invokes the...

COM Components and Scripting Process

Although this article should not concern you at all as a 'script developer' as long as you are aware of creating a reference to...

Format Decimal Numbers with Grouping Separator

The DecimalFormat class has a method called setGroupingSize() which sets how many digits of the integer part to group. Groups are separated by the...

OTHER TUTORIALS

Introduction to Apache Maven

1. What is Maven When you write a software application, there are many steps in it like adding the necessary...
- Advertisement -spot_img