Control Statements in Java - About and Types
Have you ever wondered how Java manages the flow of its programs so efficiently? The three types of control statements, namely decision-making statements, looping statements, and jump statements, allow Java programs to execute different code paths based on conditions, loop through blocks of code multiple times, and manage the flow of execution. Let's understand more!
Control statements in Java are instructions that manage the flow of execution of a program based on certain conditions. They are used to make decisions, to loop through blocks of code multiple times, and to jump to a different part of the code based on certain conditions. Control statements are fundamental to any programming language, including Java, as they enable the creation of dynamic and responsive programs.
Best-suited Java courses for you
Learn Java with these high-rated online courses
Types of Control Statements in Java
Let’s understand these three types of Control Statements in detail!
1. Decision-Making Statements
Decision-making statements in Java are constructs used to control the flow of execution based on certain conditions. They allow a program to execute different parts of code depending on whether a condition (or set of conditions) is true or false. The decision-making statements in Java are primarily of 3 types, namely: if, if-else and switch statements.
Let's discuss each one of them in detail.
1.1 'if' Statement in Java
The if statement in Java evaluates a boolean condition. If the condition is true, the block of code inside the if statement is executed. It's the simplest form of decision-making in programming, allowing for the execution of certain code based on a condition.
Syntax
if (condition) {
// Code to execute if the condition is true
}
Flowchart
For Example,
Consider a mobile recharge system where a user wants to recharge their phone. The system checks if the user has sufficient balance in their account to make the recharge. The cost of the recharge is Rs.299.
public class MobileRecharge { public static void main(String[] args) { int accountBalance = 500; // User's account balance in Rupees int rechargeAmount = 299; // Cost of the recharge
if (accountBalance >= rechargeAmount) { accountBalance -= rechargeAmount; System.out.println("Recharge successful. Remaining balance: Rs. " + accountBalance); } }}
Output
Recharge successful. Remaining balance: Rs. 201
1.2 'if-else' Statement in Java
The if-else statement in Java is used for multiple conditions. It comes after an if statement and before an else statement. If the if condition is false, the program checks the if-else condition. If the if-else condition is true, its code block is executed.
Syntax
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Flowchart
For Example,
Let's extend the mobile recharge system. If the user doesn't have enough balance for the desired recharge, the system suggests a lower-cost recharge option (e.g., Rs.149).
public class MobileRecharge { public static void main(String[] args) { int accountBalance = 200; // User's account balance in Rupees int rechargeAmount = 299; // Desired recharge amount int lowerRechargeAmount = 149; // Lower-cost recharge option
if (accountBalance >= rechargeAmount) { accountBalance -= rechargeAmount; System.out.println("Recharge successful. Remaining balance: Rs. " + accountBalance); } else if (accountBalance >= lowerRechargeAmount) { System.out.println("Insufficient balance for Rs. 299 recharge. Would you like to recharge Rs. 149 instead?"); } else { System.out.println("Insufficient balance for any recharge."); } }}
Output
Insufficient balance for Rs. 299 recharge. Would you like to recharge Rs. 149 instead?
1.3 'switch' Statement in Java
The switch statement in Java allows for the selection of a block of code to be executed based on the value of a variable or expression. It is an alternative to a series of if statements and is often more concise and easier to read.
Syntax
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
// ...
default:
// Code to be executed if expression does not match any case
}
Flowchart
For Example,
A customer orders coffee at a shop where there are three sizes available: small, medium, and large. The cost of each size is different. The system needs to calculate the bill based on the size of the coffee ordered by the customer. (Here, coffeeSize is set to "medium")
public class CoffeeShop { public static void main(String[] args) { String coffeeSize = "medium"; // Customer's choice of coffee size int price;
switch (coffeeSize) { case "small": price = 50; // Price for small size break; case "medium": price = 70; // Price for medium size break; case "large": price = 90; // Price for large size break; default: price = 0; // Default case if no size matches System.out.println("Invalid size selected."); }
if (price != 0) { System.out.println("Total bill for " + coffeeSize + " coffee: Rs. " + price); } }}
Output
Total bill for medium coffee: Rs. 70
2. Looping Statements
Looping statements in Java are used to execute a block of code repeatedly based on a given condition or set of conditions. These statements are fundamental to Java programming, allowing for iteration over data structures, repetitive tasks, and more. The main types of looping statements in Java are for loop, while loop and do-while loop.
Let's discuss each one of them in detail.
2.1 'for loop' in Java
The for loop in Java is a control structure that allows repeated execution of a block of code for a specific number of times. It is typically used when the number of iterations is known beforehand.
Syntax
for (initialization; condition; update) {
// code block to be executed
}
Here,
- Initialization: Typically used to initialize a counter variable.
- Condition: The loop runs as long as this condition is true.
- Update: Updates the counter variable, usually incrementing or decrementing.
Flowchart
For Example,
Let's say you are creating a program to calculate the factorial of a number. The factorial of a number is the product of all positive integers up to that number. The user will input a number, and you will calculate its factorial.
import java.util.Scanner;
public class FactorialCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); int factorial = 1;
for (int i = 1; i <= number; i++) { factorial *= i; // Multiplying with each number up to 'number' }
System.out.println("Factorial of " + number + " is: " + factorial); }}
Output
Enter a number: 7
Factorial of 7 is: 5040
2.2 'while loop' in Java
A while loop in Java repeatedly executes a block of code as long as a specified condition remains true. It is ideal for situations where the number of iterations is not predetermined.
Syntax
while (condition) {
// code block to be executed
}
Here,
- Condition: The loop continues to run as long as this condition evaluates to true.
- Code Block: The statements inside the loop execute repeatedly until the condition becomes false.
Flowchart
For Example,
You are given the task of developing a simple ATM PIN verification system in Java. The system should prompt the user to enter their Personal Identification Number (PIN) and validate it against a predefined correct PIN. This task simulates a common real-world scenario encountered in Automated Teller Machine (ATM) operations, focusing on user authentication through PIN verification.
import java.util.Scanner; // Import the Scanner class to read input
public class ATMPinVerificationSystem { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Create a Scanner object for reading user input final String correctPin = "1234"; // This is the correct PIN for validation boolean accessGranted = false; // Flag to track access status
// Display a welcome message System.out.println("Welcome to the ATM. Please enter your PIN:");
// The validation loop while (!accessGranted) { System.out.print("Enter PIN: "); // Prompt user to enter PIN String enteredPin = scanner.nextLine(); // Read the PIN entered by the user
if (enteredPin.equals(correctPin)) { accessGranted = true; // Correct PIN entered, grant access System.out.println("PIN accepted. Access granted."); } else { // Incorrect PIN, prompt the user to try again System.out.println("Incorrect PIN. Please try again."); } }
scanner.close(); // Close the scanner object to prevent resource leak }}
Output
Welcome to the ATM. Please enter your PIN:
Enter PIN: 1234
PIN accepted. Access granted.
2.3 'do-while loop' in Java
The do-while loop in Java is a post-tested loop, meaning it executes the body of the loop at least once before checking the condition. This loop is useful when you need to ensure that the loop body is executed at least once, regardless of whether the condition is true or false. After the body of the loop has executed, the condition is tested. If the condition is true, the loop will execute again. This process repeats until the condition becomes false.
Syntax
do {
// Statements to execute
} while (condition);
Here,
- do: This keyword starts the do-while loop.
- Statements to execute: These are the actions you want to perform. This block of code is executed on each iteration of the loop, and it is guaranteed to run at least once.
- while: This keyword is followed by a condition in parentheses.
- condition: A Boolean expression that is evaluated after the loop body has executed. If this condition evaluates to true, the loop will execute again. If it evaluates to false, the loop will terminate, and control passes to the statement immediately following the loop.
Flowchart
For Example,
Imagine you are creating a console-based application where users can select different actions from a menu. The options might include performing some actions (like viewing account details, making a transaction, etc.) and exiting the program. A do-while loop is perfect for this scenario because you want to show the menu at least once and then keep showing it after performing each action until the user decides to exit.
import java.util.Scanner;
public class MenuDrivenProgram { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int choice;
do { // Display the menu to the user System.out.println("=== Menu ==="); System.out.println("1. View account balance"); System.out.println("2. Deposit money"); System.out.println("3. Withdraw money"); System.out.println("4. Exit"); System.out.print("Enter your choice: ");
// Read the user's choice choice = scanner.nextInt();
// Perform the action based on the user's choice switch (choice) { case 1: System.out.println("Account Balance: $1000"); break; case 2: System.out.println("Deposit was successful."); break; case 3: System.out.println("Withdrawal was successful."); break; case 4: System.out.println("Exiting the program..."); break; default: System.out.println("Invalid choice. Please enter a valid option."); } } while (choice != 4); // Continue until the user chooses to exit
scanner.close(); }}
Output
=== Menu ===
1. View account balance
2. Deposit money
3. Withdraw money
4. Exit
Enter your choice: 1
Account Balance: Rs.10,000
=== Menu ===
1. View account balance
2. Deposit money
3. Withdraw money
4. Exit
Enter your choice: 3
Withdrawal was successful.
=== Menu ===
1. View account balance
2. Deposit money
3. Withdraw money
4. Exit
Enter your choice:
3. Jump Statements
Jump statements in Java are used to transfer control to another part of the program. They are particularly useful for breaking out of loops or skipping to the next iteration of a loop. The three main types of jump statements are break, continue, and return. Each serves a different purpose in controlling the flow of execution.
Let's discuss each one of them in detail.
3.1 'break' Statement in Java
The break statement is used to exit from a loop (for, while, do-while) or a switch statement. When encountered, it terminates the loop or switch statement and transfers control to the statement immediately following the loop or switch.
Syntax
break;
Flowchart
For Example,
Imagine you have a list of numbers, and you want to find out whether a specific number exists in that list. Once you find the number, you want to stop the search because there's no need to look further.
public class FindNumberInArray { public static void main(String[] args) { int[] numbers = {3, 45, 7, 8, 15, 23, 42, 87}; // An array of numbers int searchFor = 23; // The number we're searching for boolean found = false; // Flag to indicate if the number is found
for(int i = 0; i < numbers.length; i++) { if(numbers[i] == searchFor) { found = true; // The number is found System.out.println(searchFor + " found at index " + i); break; // Terminate the loop as we've found the number } }
if(!found) { System.out.println(searchFor + " not found in the array."); } }}
Output
23 found at index 5
3.2 'continue' Statement in Java
The continue statement skips the current iteration of a loop (for, while, do-while) and proceeds to the next iteration. It effectively jumps to the end of the loop's body and re-evaluates the loop's condition.
Syntax
continue;
Flowchart
For Example,
Let's say we have an array of daily sales amounts for a store, including both sales and returns. Our goal is to calculate the total of all sales while ignoring the returns.
public class TotalSalesIgnoringReturns { public static void main(String[] args) { // Array of daily sales amounts (positive for sales, negative for returns) double[] dailySales = {320.5, -100.0, 450.0, 125.0, -50.0, 600.0, 175.0}; double totalSales = 0.0; // Variable to store the total sales
for (double sale : dailySales) { if (sale < 0) { // Check if the sale amount is a return continue; // Skip this iteration (ignore the return) } totalSales += sale; // Accumulate the sales amount }
System.out.println("Total Sales (ignoring returns): Rs. " + totalSales); }}
Output
Total Sales (ignoring returns): Rs. 1670.5
3.3 'return' Statement in Java
The return statement is used to exit from a method, with or without a value. For methods that return a value, return specifies the value to return. For void methods, it causes the method to exit before reaching the end of its body.
Syntax
Syntax for Methods Returning a Value
return expression;
Here,
expression: This must evaluate to a value that is compatible with the method's declared return type. If the method is supposed to return an int, for example, the expression must evaluate to an integer value.
Syntax for Void Methods
return;
For Example,
Let's consider a simpler real-life example using the return statement in Java. Develop a Java program that can accurately determine whether a given year is a leap year. A year is considered a leap year if it is divisible by 4 but not by 100 unless it is also divisible by 400. This method takes an integer year as input and returns a boolean value to be true if the year is a leap year and false otherwise.
public class LeapYearChecker { public static void main(String[] args) { int year = 2024; // Sample year to check boolean isLeapYear = checkLeapYear(year); if (isLeapYear) { System.out.println(year + " is a leap year."); } else { System.out.println(year + " is not a leap year."); } }
public static boolean checkLeapYear(int year) { // Check if the year is a leap year if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) { return true; // It's a leap year } else { return false; // It's not a leap year } }}
Output
2024 is a leap year.
Conclusion
Thus, understanding and effectively using control statements is a key skill for any Java programmer, as they directly impact the logic, performance, and quality of the software being developed. Through learning conditional, loop, and jump statements, developers can craft solutions that are not only functional but also optimized and easy to maintain. Keep Learning, Keep Exploring!
You must explore Java Programming Courses to learn more!
FAQs
What are control statements in Java?
Control statements are programming constructs that manage the flow of execution in a Java program. They enable the program to make decisions (decision-making statements), execute a block of code multiple times (looping statements), and alter the execution flow (jump statements).
How do looping statements work in Java?
Looping statements in Java, such as the for, while, and do-while loops, allow for the repeated execution of a block of code as long as a specified condition remains true. The for loop is typically used when the number of iterations is known, whereas the while and do-while loops are used when the iterations depend on dynamic conditions.
Can you explain the difference between break and continue statements?
Both break and continue are jump statements that alter the flow of loops. The break statement exits the loop entirely, transferring control to the statement immediately following the loop. The continue statement skips the remaining code in the current iteration and proceeds to the next iteration of the loop.
When should I use a return statement in Java?
The return statement is used to exit a method and optionally pass a value back to the method caller. In void methods (methods that do not return a value), return can be used without a value to exit the method prematurely. In methods that return a value, return must be followed by a value or expression that matches the declared return type of the method. It's typically used to output the result of a computation or to exit from a method based on a condition.
What types of decision-making statements are available in Java?
Java provides several decision-making statements, such as if, if-else, switch, and nested if-else. These statements allow the program to execute certain sections of code based on conditions evaluated at runtime.
How does a switch statement differ from an if-else structure?
A switch statement is used when you have multiple potential outcomes based on the value of a single variable or expression. It's generally more readable and efficient than multiple if-else statements when dealing with numerous specific values of a single variable.
What is the purpose of nested loops in Java?
Nested loops are used when you need to perform a series of operations over a two-dimensional range of values, such as processing items in a matrix or when you want to search within search results.
Can you explain the do-while loop in Java?
The do-while loop in Java is a post-test loop, meaning the code inside the loop executes at least once before the condition is tested. It is used when the loop must run at least one time regardless of the condition being true or false.
What is an infinite loop and how can it be created in Java?
An infinite loop runs without ever terminating under its own conditions. It can be created intentionally with constructs like while(true) or for(;;) for purposes like waiting for events or polling hardware status until an external condition is met.
How can the break statement be used in nested loops?
In nested loops, a break statement will only exit the innermost loop that it resides in. To exit multiple levels of nested loops, you might need additional logic or use labeled loops where a break with a label jumps out of the specified loop.
What is the purpose of the continue statement in loops?
The continue statement skips the current iteration of the loop and proceeds with the next iteration. It is commonly used to skip over certain elements based on a condition without exiting the loop entirely.
What are labeled statements in Java and how are they used with loops?
Labeled statements are used to identify a block of code or loop. You can use labels with break or continue to control the flow of nested loops more precisely, allowing a break or continue to affect an outer loop rather than the immediately enclosing one.
When is a for-each loop more beneficial than a traditional for loop?
The for-each loop, also known as the enhanced for loop, is beneficial when you need to iterate through elements in an array or a Collection without modifying the structure of the collection. It enhances readability and reduces the likelihood of programming errors.
Can a return statement be used in loops to exit both the loop and the method?
Yes, a return statement within a loop will exit not only the loop but also the method in which the loop resides, immediately returning a value or exiting the method if it's void.
Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio