Session 5 - Conditional Statements
Session 5 - Conditional Statements
THROUGH JAVA
UNIT - I
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
}
Working of 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
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.
System.out.println("Temperature monitoring
complete.");
}
}
Program Analysis: TemperatureMonitor
1. Variable:
2. Condition Check:
3. Always Executed:
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.
Syntax
if (condition)
// Single statement to be executed if the condition is
true
Example
Example of an if statement without braces:
if (number > 0)
System.out.println("The number is
positive.");
Key Points
● 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.
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
Quiz
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
}
3. If the condition is false, execute the code inside the else block.
Flowchart
Example:
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.”
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:
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
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:
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).
(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
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
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:
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
4. Nested-if Expression
Definition
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
}
}
If condition1 is false, the program skips the entire nested if block and
moves on to the next statement outside the if structure.
Flowchart
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:
1. Outer if Statement:
The outer if statement checks if the person is 18 years or older (age >= 18).
2. Nested if Statement:
● 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:
Output:
If the age were less than 18, the output would be:
Practice Program
Write a Java program that checks if a student is eligible for a scholarship. The eligibility
criteria are as follows:
Practice Program
Program Analysis
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:
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
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
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:
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
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: ... }
6. Switch Statement
Switch Statement
Definition
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.
Flowchart
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
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:
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
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
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
A. No
B. Yes
C. Depends on the programming language
D. Depends on the compiler
Correct Answer: A. No
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