0% found this document useful (0 votes)
7 views50 pages

Session 5 - Conditional Statements

The document provides an introduction to conditional statements in Java, explaining their role in controlling program flow based on specific conditions. It covers various types of conditional statements, including 'if', 'if-else', and 'if-else if', along with syntax, real-time examples, and best practices for implementation. Additionally, it includes practice programs and quizzes to reinforce understanding of these concepts.

Uploaded by

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

Session 5 - Conditional Statements

The document provides an introduction to conditional statements in Java, explaining their role in controlling program flow based on specific conditions. It covers various types of conditional statements, including 'if', 'if-else', and 'if-else if', along with syntax, real-time examples, and best practices for implementation. Additionally, it includes practice programs and quizzes to reinforce understanding of these concepts.

Uploaded by

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

OBJECT-ORIENTED PROGRAMMING

THROUGH JAVA

UNIT - I

Session 5 - Conditional Statements

1. Introduction to conditional statements

Introduction to control statements:


Conditional statements in programming manage a program's flow by evaluating specific
conditions. These statements enable different code blocks to run depending on whether
a given condition is true or false, offering a key tool for algorithm decision-making. Let’s
explore the fundamentals of conditional statements and their various types.
Real-time example:
We encounter conditionals in every aspect of our daily lives, where we make decisions
based on specific conditions. For example, "If it is raining, stay at home; otherwise, go
outside," or “If you study well for the exam, you will get good marks” or "If today is
Sunday, there is no need to go to college; otherwise, go to college ." Another example is,
"If the Indian team's score is greater than the England team's score, then 'India won the
match'; if it is less, then 'England won the match'; otherwise, the 'Match is a draw. '"

Similarly, we encounter many such conditions in our everyday life.


Types of Conditional Statements:
Common types of conditional statements are
1. if statement
2. if-else statement
3. If-else-if statement (nested if)
4. switch statement
5. Ternary operator
2. Simple ‘if’ Expression

Simple if Expression:

Definition

The if statement in Java is a basic control flow structure that allows you to execute a
block of code only when a specified condition is true. It helps in decision-making within
a program, enabling dynamic and conditional behavior based on different inputs or
states.

Real-Time Example
Consider a temperature monitoring system in a server room. The system needs to
check if the temperature is above a certain threshold (e.g., 75 degrees Fahrenheit). If
the temperature exceeds this limit, it should trigger an alert to notify that the
temperature is too high. This scenario can be implemented using a simple if statement
in Java.

Syntax

if (condition) {
// Code to be executed if the condition is true
}

Condition: A boolean expression that evaluates to either true or false. If the


condition is true, the block of code inside the if statement is executed. If false, the
block is skipped.

Working of if Statement

1. The program checks the condition specified in the if statement.

2. If the condition evaluates to true, the code inside the if block is executed.

3. If the condition evaluates to false, the code inside the if block is skipped, and

the program continues with the next statement after the if block.
Flowchart

Example

Here’s an example of a simple if statement in Java for the temperature monitoring


system:

if (number % 2 == 0) {
System.out.println("The number is even.");
}
Key Points:

- The if statement only executes the block of code if the specified condition is
true.
- The code inside the if block should be enclosed in curly braces {}. However,
for single statements, curly braces are optional, but using them is considered a
good practice for code readability and to avoid errors.
- The condition in the if statement must evaluate to a boolean value (true or
false). Non-boolean expressions cannot be used as conditions.

Practice program
The below program checks the temperature and gives alert message if the temperature
is greater than 75 degrees Farenheit.

public class TemperatureMonitor {


public static void main(String[] args) {
int temperature = 80; // Current temperature in
degrees Fahrenheit

// Check if the temperature exceeds the safe limit


if (temperature > 75) {
System.out.println("Alert: Temperature is too
high! Please check the cooling system.");
}

System.out.println("Temperature monitoring
complete.");
}
}
Program Analysis: TemperatureMonitor

The TemperatureMonitor program checks if the current temperature is above a


certain threshold and prints an alert if it is.

1. Variable:

int temperature = 80;: Stores the current temperature.

2. Condition Check:

Condition: if (temperature > 75)


Action: If temperature is greater than 75, print "Alert:
Temperature is too high! Please check the cooling
system."

3. Always Executed:

After the if statement, the program prints "Temperature monitoring


complete." regardless of the condition.

4. Output:
Using if Without Braces

In Java, the curly braces {} define a block of code that should be executed when a
condition is met in an if statement. However, the braces can be omitted if there is
only one statement to execute. This can make the code more concise but may affect
readability and maintainability.

Here’s a detailed look at using if statements without braces:

Syntax

if (condition)
// Single statement to be executed if the condition is
true

● Condition: A boolean expression that evaluates to true or false.


● Single statement: The code that will run if the condition is true. No
braces are needed if there’s only one statement.

Example
Example of an if statement without braces:
if (number > 0)
System.out.println("The number is
positive.");

Key Points

● Single Statement: Omitting braces is allowed when the if statement controls a


single statement. This can make the code more compact.
● Readability: Omitting braces can reduce readability, especially in more complex
code or when multiple developers are involved. It can also lead to errors if
additional statements are added later without proper braces.

● Best Practice: Braces are generally recommended for better readability and to
avoid potential mistakes, even if there's only one statement inside the if block.

Practice Program
Write a Java program that checks if a number is positive. If it is, print "The number is
positive."

Hint: Use the if statement without braces for simplicity, but ensure you understand
how it affects the control flow.

public class IfWithoutBracesExample {


public static void main(String[] args) {
int number = 10;

// Check if the number is positive


if (number > 0)
System.out.println("The number is positive.");

System.out.println("This statement is always


executed.");
}
}
Program Analysis:

This program checks if the number is positive and prints a message if it is.

1. Variable:
○ int number = 10;: Holds the value to check.
2. Condition Check:
○ if (number > 0): Checks if number is greater than 0.
3. Code Execution:
○ If Condition True: Prints "The number is positive." because
number is 10.
○ Always Executed: Prints "This statement is always
executed." regardless of the condition.
4. Output

Do It Yourself

1. Create a program to determine whether a person is eligible for a discount for a


senior citizen
2. Write a Java program that checks if the gravity on a planet is greater than 9.8
m/s². If it is, print "The gravity is stronger than Earth's gravity."
3. Write a Java program to check if the speed of light in a medium is less than
300,000 km/s. If it is, print "The speed of light in this medium is less than in a
vacuum."
4. Write a Java program to check if the altitude is above 5000 meters. If it is, print
"You are at a high altitude.".

Quiz

1. What is the purpose of the if statement?


A. To perform calculations
B. To store data
C. To make decisions based on a condition
D. To output results

Correct Answer: C. To make decisions based on a condition

2. What happens if the condition in an if statement is false?


A. The code inside the if block is executed
B. The code inside the if block is skipped
C. An error occurs
D. The program terminates

Correct Answer: B. The code inside the if block is skipped

3. How is the condition in an if statement typically expressed?


A. As a mathematical equation
B. As an integer
C. As a string
D. As a boolean expression

Correct Answer: D. As a boolean expression

4. What are the curly braces used for in an if statement?


A. To enclose the condition
B. To enclose the code to be executed
C. To define a new block of code
D. To indicate the end of the program

Correct Answer: B. To enclose the code to be executed

5. What will be the output of the following Java code?

public class Test {


public static void main(String[] args) {
int score = 90;

if (score > 85)


System.out.println("Excellent score!");
System.out.println("Good job!");
}
}

A. Excellent score! Good job!


B. Excellent score!
C. Good job!
D. No output

Correct Answer: A. Excellent score! Good job!

3. ‘if-else’ Expression
if-else Expression in Java

Definition

The if-else statement in Java is a control flow statement that allows you to execute
one block of code if a specified condition is true and another block if the condition is
false. It provides an alternative path of execution in case the original condition does not
hold, making it a fundamental construct for decision-making in programming.

Real-Time Example
Consider a real-time example of a simple automated teller machine (ATM) system. The
system checks a user's balance before allowing a withdrawal. If the user's balance is
sufficient, the system processes the withdrawal; otherwise, it displays an error message
indicating insufficient funds.

Syntax

if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}

● Condition: A boolean expression that evaluates to true or false.


● if block: The code within this block executes if the condition is evaluated
as true.
● else block: The code within this block executes if the condition is
evaluated as false.

Working of if-else Statement

1. Evaluate the condition.


2. If the condition is true, execute the code inside the if block.

3. If the condition is false, execute the code inside the else block.

Flowchart

Below is a simplified flowchart representing the working of an if-else statement:

Example:

Here's a Java code snippet demonstrating the use of an if-else statement:

if (withdrawalAmount <= balance) {


balance -= withdrawalAmount; // Deduct the
amount from balance
System.out.println("Withdrawal successful. New
balance: " + balance);
} else {
System.out.println("Insufficient funds. Unable
to process withdrawal.");
}

Key Points

- The if block is executed only when the condition is true. If the condition is
false, the else block is executed.
- The else part of the statement is optional. If no alternative action is required,
you can use an if statement without an else block.
- The condition in the if statement must evaluate to a boolean value (true or
false). Conditions using other data types will result in a compilation error.
- Proper indentation and use of braces {} enhance code readability and reduce
the risk of logical errors, especially when adding more complex conditions or
statements later.

Practice Program
Java program that checks if a person is eligible to vote. If the person’s age is 18 or
above, print “You are eligible to vote.” Otherwise, print “You are not eligible to vote.”

public class VotingEligibility {


public static void main(String[] args) {
int age = 16; // Person's age

// Check if the person is eligible to vote


if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to
vote.");
}
}
}

Program Analysis

1. Variable Declaration:

The program declares an integer variable age and assigns it a value of 16.

2. Condition Check:

The if statement checks whether the age is 18 or older (age >= 18).

3. Condition Evaluation:

The condition age >= 18 evaluates to false because age is 16.

4. else Block Execution:

Since the condition is false, the code inside the else block is executed,
printing “You are not eligible to vote.”

5. Output:

By understanding the if-else statement, you can write programs that make decisions
based on different conditions, making your code dynamic and adaptable to various
scenarios.
4. if...else...if Statement

if-else if Ladder:

Definition

The if-else if ladder is a series of conditional statements that allows a program to


evaluate multiple conditions sequentially. Each condition is tested in order, and when a
condition evaluates to true, the corresponding block of code is executed. If none of the
conditions are true, the else block (if present) is executed. This structure is useful
when multiple possible outcomes are based on different conditions.

Real-Time Example
Consider a grading system for a school where students are assigned grades based on
their marks. The system needs to evaluate several conditions:

● If the marks are 90 or above, the grade is 'A'.


● If the marks are between 80 and 89, the grade is 'B'.
● If the marks are between 70 and 79, the grade is 'C'.
● If the marks are between 60 and 69, the grade is 'D'.
● If the marks are below 60, the grade is 'F'.

Syntax
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else if (condition3) {
// Code to be executed if condition3 is true
}
// More else if statements can be added as needed
else {
// Code to be executed if all conditions are false
}
Working of if-else if Ladder Statement
1. The program starts by evaluating the first condition (condition1).

2. If condition1 is true, the corresponding block of code is executed, and the


rest of the ladder is skipped.
3. If condition1 is false, the program proceeds to check the next condition

(condition2).
4. This process continues down the ladder until a true condition is found.

5. If none of the conditions are true, the else block (if present) is executed.

6. Once a condition evaluates to true and its block is executed, the rest of the
ladder is skipped.
Flowchart
Example Code Snippet

public class GradingSystem {


public static void main(String[] args) {
int marks = 85; // Example marks

if (marks >= 90) {


System.out.println("Grade: A");
} else if (marks >= 80) {
System.out.println("Grade: B");
} else if (marks >= 70) {
System.out.println("Grade: C");
} else if (marks >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
}
}

Program Analysis

The example program demonstrates how the if-else if ladder evaluates each
condition in sequence:

● The first condition checks if marks are greater than or equal to 90.
● If this condition is false, the next condition checks if marks are greater than or
equal to 80.
● This process continues until a true condition is found or all conditions are
evaluated.
● The example ends with an else block to handle the case when none of the
specified conditions are met.

Output:
Key Points

● The if-else if ladder allows checking multiple conditions sequentially, and


only one condition will be executed based on the first true match.
● If a match is found in one of the conditions, the rest of the else if conditions
and the else block (if present) are skipped.
● If all conditions are false, and there is no else block, no code is executed from
the ladder.
● This structure is ideal for scenarios where multiple conditions are mutually
exclusive.

Practice Example
Write a Java program that checks the age of a person and prints whether they are a
child, teenager, adult, or senior based on the following conditions:

● Age less than 13: "Child"


● Age between 13 and 19: "Teenager"
● Age between 20 and 59: "Adult"
● Age 60 and above: "Senior"

public class AgeCategory {


public static void main(String[] args) {
int age = 25; // Example age

if (age < 13) {


System.out.println("Child");
} else if (age >= 13 && age <= 19) {
System.out.println("Teenager");
} else if (age >= 20 && age <= 59) {
System.out.println("Adult");
} else if (age >= 60) {
System.out.println("Senior");
}
}
}

Program Analysis
1. Variable Declaration:
● int age = 25;: Defines the age of the person to check. You can change this
value to test different cases.

2. Condition Checks:
● First Condition: if (age < 13) checks if the age is less than 13. If true,
prints "Child".
● Second Condition: else if (age >= 13 && age <= 19) checks if the
age is between 13 and 19. If true, prints "Teenager".
● Third Condition: else if (age >= 20 && age <= 59) checks if the age is
between 20 and 59. If true, prints "Adult".
● Fourth Condition: else if (age >= 60) checks if the age is 60 or above. If
true, prints "Senior".

3. Output:

● Based on the value of age, the program outputs the corresponding category. For
age = 25, the output will be:

By understanding the if-else if ladder, you can create Java programs that make
complex decisions based on multiple criteria, making your applications more flexible
and responsive to user input and conditions.

Do It Yourself
1. Develop a simple program to calculate overtime pay based on the number of
hours worked.
2. Write a Java program to Classify a Temperature as Hot, Warm, or Cold
3. Write a Java program that checks whether a bank account balance exceeds the
required minimum balance of $100. If the balance is greater than or equal to
$100, print "Account is in good standing." Otherwise, print "Account balance is
below the minimum required."
4. Write a Java program that takes a user's input for a password and checks if it
matches a predefined password. If the input matches, print "Access granted."
Otherwise, print "Access denied."

Quiz

1. What is the purpose of the else block in an if-else statement?


A. To provide an alternative action when the condition is true
B. To provide an alternative action when the condition is false
C. To create an infinite loop
D. To terminate the program

Correct Answer: B. To provide an alternative action when the condition is


false

2. Can an if statement exist without an else block?


A. Yes
B. No
C. Depends on the programming language
D. Depends on the compiler

Correct Answer: A. Yes

3. How is the condition in an if-else statement typically expressed?


A. As a mathematical equation
B. As a string
C. As an integer
D. As a boolean expression

Correct Answer: D. As a boolean expression

4. What is the importance of code indentation in an if-else statement?


A. It is required by the compiler
B. It affects program execution
C. It improves code readability
D. It has no impact on the code

Correct Answer: B. It improves code readability

4. Nested-if Expression

Nested if Expression in Java

Definition

A nested if expression is an if statement placed inside another if statement. This


structure allows for more complex decision-making processes where multiple conditions
need to be evaluated in a hierarchical manner. In a nested if expression, the inner if
statement is only evaluated if the outer if statement's condition is true. This is useful
when decisions depend on multiple layers of conditions.

Real-time Example
Imagine a school grading system where students receive different levels of rewards
based on their scores. For example, if a student's score is above 90, they get a
"Distinction." However, if their score is above 90 and they also have perfect attendance,
they receive an "Excellence Award." This scenario can be handled using a nested if
statement to check both conditions sequentially.

Syntax

if (condition1) {
// Code to be executed if condition1 is true
if (condition2) {
// Code to be executed if condition1 and condition2
are true
}
}

● condition1: The first condition to be evaluated.


● condition2: The second condition that is only evaluated if condition1 is true.

Working of 'Nested-if Expression' Statement

1. Evaluate the Outer Condition (condition1):

The program first checks the outer if statement's condition. If condition1 is


true, it proceeds to evaluate the nested if statement.

2. Evaluate the Inner Condition (condition2):

If condition1 is true, the program then checks the inner if statement's


condition. If condition2 is also true, the code inside the inner if block is
executed.

3. Skip the Nested Block if Outer Condition is False:

If condition1 is false, the program skips the entire nested if block and
moves on to the next statement outside the if structure.
Flowchart

Here is the flowchart representation of a nested if statement:

Key Points

● Readability: While nested if statements can handle complex logic, they can
also make code harder to read and maintain. It's often a good practice to refactor
deeply nested code into separate methods or functions for clarity.
● Performance: In most cases, nested if statements do not impact performance
significantly, but overly complex nested structures can slow down execution,
particularly if multiple conditions must be checked repeatedly.

Example:

Let's consider a real-world scenario where we determine the eligibility of a person to


donate blood. The criteria for blood donation are as follows:

● The person must be at least 18 years old.


● The person must weigh at least 50 kg.

Example: Blood Donation Eligibility

public class BloodDonationEligibility {


public static void main(String[] args) {
int age = 25; // Age of the person
int weight = 55; // Weight of the person in kg

// Outer if statement checks the age condition


if (age >= 18) {
// Nested if statement checks the weight condition
if (weight >= 50) {
System.out.println("You are eligible to donate
blood.");
} else {
System.out.println("You are not eligible to
donate blood due to insufficient weight.");
}
} else {
System.out.println("You are not eligible to donate
blood due to age restrictions.");
}

System.out.println("Blood donation eligibility check


complete.");
}
}
Explanation

1. Outer if Statement:

The outer if statement checks if the person is 18 years or older (age >= 18).

● If this condition is true, the program proceeds to the nested if


statement.
● If the condition is false, the else block is executed, indicating the
person is too young to donate blood.

2. Nested if Statement:

The nested if statement checks if the person's weight is 50 kg or more (weight


>= 50).

● If this condition is true, the program prints that the person is eligible to
donate blood.
● If the condition is false, the else block is executed, indicating the
person is not eligible due to insufficient weight.

3. Program Flow:

● The program first evaluates the outer if condition (age).


● If the age condition is met, it evaluates the nested if condition (weight).
● Depending on the results of these evaluations, the program prints the
appropriate message to the console.

Output:
If the age were less than 18, the output would be:

And if the weight were less than 50:

Practice Program
Write a Java program that checks if a student is eligible for a scholarship. The eligibility
criteria are as follows:

- The student must have a GPA of 3.5 or above.


- The student must have completed at least 30 credit hours.
- If both conditions are met, the student is eligible for a scholarship.

Practice Program

public class ScholarshipEligibility {


public static void main(String[] args) {
double gpa = 3.8; // Student's GPA
int creditHours = 40; // Student's completed credit
hours

// Outer if statement checks the GPA condition


if (gpa >= 3.5) {
// Nested if statement checks the credit hours
condition
if (creditHours >= 30) {
System.out.println("You are eligible for a
scholarship.");
} else {
System.out.println("You are not eligible for a
scholarship due to insufficient credit hours.");
}
} else {
System.out.println("You are not eligible for a
scholarship due to a low GPA.");
}

System.out.println("Scholarship eligibility check


complete.");
}
}

Program Analysis

1. GPA Check (Outer if Statement):

● The program first checks if the student's GPA is 3.5 or higher.


● If this condition is met (gpa >= 3.5), the program proceeds to check the
next condition.

2. Credit Hours Check (Nested if Statement):


● The nested if statement checks if the student has completed 30 or more
credit hours (creditHours >= 30).
● If this condition is met, the program prints that the student is eligible for a
scholarship.

3. Decision Points:

● If the GPA condition is not met, the program immediately prints that the
student is ineligible due to a low GPA and skips the nested if.
● If the GPA is sufficient but the credit hours are not, the program prints that
the student is ineligible due to insufficient credit hours.

4. Conclusion:

- This program demonstrates how a nested if structure can be used to


evaluate multiple dependent conditions in a decision-making process.

By using nested if statements, you can create more detailed and nuanced logic flows
in your Java programs, enabling more complex decision-making capabilities that are
useful in real-world applications.

Do It Yourself
1. Develop a simple grading system with multiple grade ranges.
2. Write a program for Bank Account Transactions using nested if

Quiz
1. What is the purpose of nested if statements?
A. To simplify code
B. To create multiple decision points
C. To avoid using else statements
D. To improve program efficiency

Correct Answer: B. To create multiple decision points

2. How many levels of nesting can be used in Java?


A. There is no limit
B. Limited to 5 levels
C. Limited to 10 levels
D. Depends on the compiler

Correct Answer: A. There is no limit (practically limited by code


readability)

3. What is the importance of indentation in nested if statements?


A. It improves code readability
B. It is required by the compiler
C. It affects program execution
D. It has no impact on the code

Correct Answer: A. It improves code readability

4. When would you use nested if statements instead of a single if


statement?
A. For simple conditions
B. To improve program performance
C. To avoid using else statements
D. For complex conditions with multiple possibilities

Correct Answer: D. For complex conditions with multiple possibilities


5. Ternary operator

Ternary Operator
The ternary operator in Java is a concise way to perform conditional evaluations. It’s
often used as a shorthand for the if-else statement.

Definition

The ternary operator is a conditional operator that provides a compact syntax for
evaluating a boolean expression and returning one of two values based on the result. It
is sometimes referred to as the conditional operator.

Syntax

condition ? expression1 : expression2


● condition: A boolean expression that evaluates to true or false.
● expression1: The value returned if the condition is true.
● expression2: The value returned if the condition is false.

Example
int a = 10;
int b = 20;
int max = (a > b) ? a : b;
System.out.println(max);

In this example, (a > b) is the condition. If a is greater than b, then a will be assigned
to max; otherwise, b will be assigned to max. Since a (10) is not greater than b (20),
max will be assigned the value of b, which is 20.

Practice Program:

public class TernaryOperatorExample {


public static void main(String[] args) {
int age = 18;
String result = (age >= 18) ? "Adult" : "Minor";
System.out.println(result);
}
}

Program Analysis:

1. Condition: (age >= 18) evaluates whether the variable age is greater than or
equal to 18.
2. True Case: If age is 18 or older, the expression "Adult" is chosen.
3. False Case: If age is less than 18, the expression "Minor" is chosen.
4. Output: Since age is 18, the condition evaluates to true, so the output is
"Adult".

Explanation:
This program uses the ternary operator to determine if the value of age qualifies as
"Adult" or "Minor". The ternary operator simplifies the code by replacing a multi-line if-
else statement with a single line of code, making it more concise and readable.

Do It Yourself

1. Write a Java program that takes two integer inputs and uses a ternary
operator to find and print the maximum of the two numbers.
2. Write a Java program that uses a ternary operator to assign a grade based
on a student's score. The grading criteria are as follows:
● If the score is 90 or above, the grade is 'A'.
● If the score is 80 to 89, the grade is 'B'.
● If the score is 70 to 79, the grade is 'C'.
● If the score is below 70, the grade is 'D'.

Quiz

1. What is the purpose of the ternary operator?


A. To replace loops
B. To create functions
C. To provide a concise conditional expression
D. To handle exceptions
Correct Answer: B. To provide a concise conditional expression

2. Which of the following is the correct syntax for the ternary operator?
A. condition ? expression1 : expression2
B. if (condition) expression1 else expression2
C. condition then expression1 else expression2
D. switch (condition) { case expression1: ... }

Correct Answer: A. condition ? expression1 : expression2

3. Can you nest ternary operators?


A. Yes
B. No
C. Depends on the programming language
D. Depends on the compiler

Correct Answer: A. Yes

4. When is it generally recommended to use the ternary operator?


A. For complex conditional logic
B. For input/output operations
C. For simple conditional assignments
D. For array manipulations

Correct Answer: C. For simple conditional assignments

6. Switch Statement
Switch Statement

Definition

A switch statement in Java is a control flow statement that allows a variable to be


tested for equality against a list of values. Each value is called a "case," and the
variable being switched on is checked for each case. The switch statement is an
alternative to using multiple if-else statements and is often more readable and
efficient when dealing with multiple conditions that depend on a single variable.

Real-Time Example
Consider a simple calculator application that performs different mathematical operations
based on user input. The user selects an operation (like addition, subtraction,
multiplication, or division), and the program executes the corresponding operation using
a switch statement.

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;
// You can have any number of case statements.
default:
// Code to be executed if expression doesn't match any
case
}
● expression: The variable or expression whose value is compared against each
case.
● value1, value2, ...: Constant values that the expression is compared
to.
● break: Terminates the current case block, preventing the execution from falling
through to subsequent cases.
● default: Optional. This block is executed if none of the cases match the
expression.

Working of Switch Statement

1. Evaluate the Expression: The switch statement evaluates the expression


provided in the parentheses.
2. Compare with Cases: The value of the expression is then compared against the

values of each case.


3. Execute Matching Case: If there is a match, the code block corresponding to

that case is executed.


4. Break Statement: After executing the matching case block, the break

statement prevents the code from continuing to the next case.


5. Default Case: If no cases match, the default block is executed (if provided).

Flowchart

The flowchart of a switch statement is as follows:


Example Code Snippet
Here's a snippet that demonstrates the use of a switch statement to determine the day
of the week:

int day = 3; // Example day

switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
break;
}

Key Points

● The switch statement is often preferred over a series of if-else statements


when all the conditions are based on the same expression.
● The break statement is crucial to prevent "fall-through" behavior, where multiple
cases execute in sequence.
● The default case is optional but recommended to handle unexpected values.
● The expression used in a switch must evaluate to a char, byte, short, int, or
String (or their corresponding wrapper classes).

Practice Example

Write a Java snippet that uses a switch statement to print the name of a month based
on an integer input ranging from 1 to 12. If the input is outside this range, print "Invalid
month."
Here is the Java code for the above that uses a switch statement to print the name of
a month based on an integer input ranging from 1 to 12:

import java.util.Scanner; // Import the Scanner class

public class MonthNameExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create a
Scanner object for user input

System.out.print("Enter a number (1-12) to get the


corresponding month: ");
int month = scanner.nextInt(); // Read user input as
an integer

// Use switch statement to determine the month name


switch (month) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("Invalid month"); //
Executes if input is not in the range 1-12
break;
}

scanner.close(); // Close the Scanner object


}
}

Program Analysis
● Input: The program takes an integer input from the user, which represents a
month number (1 to 12).
● Process: The switch statement checks the input against each case (1 through
12) to determine the corresponding month name.
● Output:
○ If the input is between 1 and 12, the program prints the corresponding
month name.
○ If the input is outside this range, the program prints "Invalid month."
Eg. For example

This program effectively demonstrates the use of a switch statement to handle


multiple possible values of a single variable, providing clear and efficient control flow.

By using a switch statement in the practice example, you efficiently handle multiple
possible values for the input variable with a clear and concise structure.

Do It Yourself
1. Develop a simple calculator with basic operations using a switch statement.
2. Create a program to classify beauty products based on their category using a switch
statement.

Quiz

1. What is the purpose of the switch statement?

A. To perform calculations
B. To make decisions based on multiple possible values
C. To create loops
D. To handle exceptions
Correct Answer: B. To make decisions based on multiple possible values

2. What is the role of the break statement in a switch case?

A. To continue to the next case


B. To create an infinite loop
C. To perform calculations
D. To exit the switch block

Correct Answer: D To exit the switch block

3. Can you use a floating-point number as the expression in a switch


statement?

A. No
B. Yes
C. Depends on the programming language
D. Depends on the compiler

Correct Answer: A. No

4. What happens if no case matches the expression in a switch


statement?

A. The program terminates


B. The next case is executed
C. The default case (if present) is executed
D. An error occurs

Correct Answer: C. The default case (if present) is executed

References
If statements - if Statement in Java
If-else Expressions - #12 If else in Java
If-else-if ladder - #13 If Else If in Java
Switch statement - #15 Switch Statement in Java
Nested if Statement - Nested if-else Statements in Java

End of Session - 5

You might also like