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

Concatenate Strings Using String.join() for Collections

There is an overloaded version of the String.join method that accepts as parameter an Iterable implementation. Since all Collection classes implement the Iterable interface,...

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

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

Java Tutorial #6 – Jump Statements

Introduction The break statement is used to stop further execution. It can be used either in a loop or within a switch statement. Break Statement The break...

Â

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 Common Commands Reference

Maven offers a good set of commands and CLI Options to carry out wide range of Dev tasks. Most of these commands are in...

Java Tutorial #5 – Loop Statements

Iteration statements are used to repeat a particular block of code until a certain condition is true. In this article, we will be taking...

Java Tutorial #3 – Java Arrays

Table of Contents One Dimensional Array Declaring Array Allocting Memory to Array Accessing Array Elements Initializing Array Length of Array Multi Dimensional Array Creating 3...

VBS Part 1 – Introduction and Background

At the upfront, this theoretical article might look boring to most of us but still, it is advisable to know about our scripting friend...

OTHER TUTORIALS

Automation Tools Comparison (SilkTest vs QTP vs Selenium)

While manual testing and automated testing go hand in hand, one of the important benefits of automated testing is...
- Advertisement -spot_img