0% found this document useful (0 votes)
13 views28 pages

Control Statements in Java - About and Types: Esha Gupta

Uploaded by

Raja Prasant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views28 pages

Control Statements in Java - About and Types: Esha Gupta

Uploaded by

Raja Prasant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Control Statements in Java - About and Types

Esha Gupta
Associat e Senior Execut ive
Updated on Sep 12, 2024 16:26 IST
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.

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Cont rol St at ement s in C | Meaning and Types
Co ntro l statements in C are used to determine the o rder in which the
instructio ns within a pro gram are executed. They are o f three types: Selectio n,
Iteratio n & Jump statements. Think...re ad m o re

Types of Control Statements in Java


Decision-Making Statements
Looping Statements

Jump Statements
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) {

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
// 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.

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Copy code

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
}

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
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).

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Copy code

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 = 14 9; // 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. 14 9 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

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
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

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
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")

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Copy code

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

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
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 f or loop, while
loop and do-while loop.
Let's discuss each one of them in detail.

2.1 'for loop' in Java


The f or 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

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
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.

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Copy code

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
specif ied condition remains true. It is ideal f or situations where the
number of iterations is not predetermined.

Syntax

while (condition) {

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
// 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 f alse.
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.

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Copy code

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


}
}

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
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 perf orm.
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 f ollowed by a condition in parentheses.

condition: A Boolean expression that is evaluated af ter the loop


body has executed. If this condition evaluates to true, the loop will
execute again. If it evaluates to f alse, the loop will terminate, and
control passes to the statement immediately f ollowing the loop.

Flowchart

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
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.

Copy code

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

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
System.out.println("\n=== 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();
}
}

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
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.

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
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.

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Copy code

public class FindNumberInArray {


public static void main(String[] args) {
int[] numbers = {3, 4 5, 7, 8, 15, 23, 4 2, 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

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
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.

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Copy code

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, 4 50.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

Get t ing St art ed wit h Java Hello World Program


Do yo u kno w the significance o f the "Hello Wo rld" pro gram in Java? It's the first
step fo r many into the wo rld o f pro gramming, serving as a simple yet pro fo und
intro ductio n...re ad m o re

All About Java Synt ax


Have yo u ever wo ndered ho w Java, o ne o f the mo st po pular pro gramming
languages, structures its co de? Understanding Java syntax is key to this,
enco mpassing a set o f precise rules and...re ad m o re

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Underst anding Java Main Met hod
Have yo u ever wo ndered ho w a Java applicatio n begins its executio n? The key
lies in the Java main metho d, public static vo id main(String[] args), which serves
as the gateway fo r...re ad m o re

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 f or 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 f or 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 f alse otherwise.

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Copy code

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 % 4 00 == 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.

Learning Lit erals in Java


Do yo u kno w that the unchangeable values written directly into yo ur co de are
called literals in Java? These include numbers like 10 0 , wo rds like "Java", o r
bo o leans like true, and...re ad m o re

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
Java Comment s | About , Types and Examples
Do yo u kno w what makes the co de mo re readable? Co mments, as they pro vide
valuable co ntext and explanatio ns abo ut the co de, making it easier fo r bo th the
o riginal develo pers and o thers...re ad m o re

What are Ident if iers in Java?


Have yo u ever wo ndered ho w Java keeps everything o rganized and
accessible? It's all because o f identifiers. Tho se unique labels assigned to
variables, metho ds, and classes. These crucial elements o f Java...re ad m o re

Underst anding Variables in Java


Have yo u ever wo ndered ho w data is sto red and manipulated in Java
pro grams? Variables in Java are the answer, acting as co ntainers fo r data
values. Each variable is defined with...re ad m o re

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?

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
How do looping statements work in Java?

Can you explain the dif f erence between break and continue
statements?

When should I use a return statement in Java?

What types of decision-making statements are available in Java?

How does a switch statement dif f er f rom an if -else structure?

What is the purpose of nested loops in Java?

Can you explain the do-while loop in Java?

What is an inf inite loop and how can it be created in Java?

How can the break statement be used in nested loops?

What is the purpose of the continue statement in loops?

What are labeled statements in Java and how are they used with
loops?

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.
When is a f or-each loop more benef icial than a traditional f or loop?

Can a return statement be used in loops to exit both the loop and the
method?

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 13-Sep-20 24.

You might also like