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

How To Remove Duplicates From List in Java

Introduction A List is an interface in the Java collection framework which can be used to store a group of objects. A List is ordered...

Concatenate Strings Using StringBuilder.append()

In addition to String, Java has the java.lang.StringBuffer and java.lang.StringBuilder classes. These can also be used to concatenate Strings. The advantage of these...

Concatenate Strings Using String Joiner

Java 8 has added a new class called StringJoiner. This concatenates Strings using a delimiter as well as adds a prefix and suffix to...

Remove Duplicates from List Using Set.addAll

The Set interface has a method called addAll. This accepts a 'Collection' as the parameter. So if you invoke this method by passing the...

Â

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

Convert List to Array Using ToArray Without Param

Java provides a toArray method on the 'List' interface. This can be used to convert a 'List' to an array. Since there are are...

How To Sort List in Java

Introduction A List is an interface in the Java collection framework. It can be used to store objects. Programmers often encounter scenarios where they need...

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...

Java Tutorial #1 – Variables and Data Types

Table of Contents Introduction 1. Variables 2. Data Types Primitive Data Types Integer Data Types Decimal Data Types Character Data Types Boolean Data Types Reference...

OTHER TUTORIALS

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...

Project Contributors

- Advertisement -spot_img