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

Rounding Decimal Number With Java DecimalFormat

The DecimalFormat class has a method called setRoundingMode() which can be used for setting the rounding mode for DecimalFormat object. The setRoundingMode() accepts RoundingMode...

Remove Duplicates from List Using LinkedHashSet

Another implementation of the Set interface is LinkedHashSet. LinkedHashSet maintains the order of elements and helps to overcome the HashSet limitation. The following code...

Introduction to Apache Maven

1. What is Maven When you write a software application, there are many steps in it like adding the necessary JAR files, compiling the source...

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

Â

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

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

Concatenate Strings Using String.join()

Java 8 has added a static join method to the String class. This concatenates Strings using a delimiter. Performance wise, it is similar to...

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

What is In-Proc and Out-Proc (COM) ?

The terms 'In-Proc' and 'Out-Proc' are to describe the kind of implementation of COM Servers. Before we begin, for those who are not quite...

OTHER TUTORIALS

How To Set XAMPP To Run As-Admin By Default

Why run XAMPP as-admin The XAMPP is recommended to be executed as-admin as it requires running a couple of system...

Java DecimalFormat Class

- Advertisement -spot_img