Java Programming Step 4
Java Conditional Statements
Introduction
Java Conditional Statements are used to make decisions in a program. They allow Java programs to execute different blocks of code depending on whether a condition is true or false.
In the previous lesson, Step 3: Java Operators and Input/Output, you learned how to use operators, take user input with Scanner, and display output. Now you will use those concepts to build programs that can make decisions.
In this Step 4 Java Programming Tutorial, you will learn if, if-else, else-if, nested if, multiple conditions, logical operators with conditions, the ternary operator, switch, modern switch expressions, common mistakes, practical programs, exercises, and a mini project.
What You Will Learn
After completing this lesson, you will understand:
- What conditional statements are
- The if statement
- The if-else statement
- The else-if ladder
- Multiple conditions
- Nested if
- Logical operators in conditions
- Relational operators in conditions
- Equality conditions
- Ternary operator
- Traditional switch
- case
- break
- default
- Modern switch expressions
- yield
- switch with String
- switch with enum
- Common conditional statement mistakes
- Practical Java programs
- Exercises
- Mini project
What Are Conditional Statements?
A conditional statement allows a program to make a decision.
For example, suppose you want to check whether a student has passed an exam.
The logic could be:
↓
Student Passed
Otherwise
↓
Student Failed
Java uses conditional statements to implement this type of logic.
The most common conditional structures are:
if-else
else-if
nested if
switch
Why Are Conditional Statements Important?
Without conditions, most programs would execute the same instructions every time.
Conditional statements allow programs to respond differently to different situations.
For example:
- Check whether a user is old enough.
- Check whether a password is correct.
- Determine whether a number is even or odd.
- Calculate a student's grade.
- Check whether a product is available.
- Select a menu option.
- Determine a discount.
- Validate user input.
Conditional statements are therefore fundamental to programming.
The if Statement
The simplest conditional statement in Java is if.
Syntax:
// code executed when condition is true
}
Example:
if (age >= 18) {
System.out.println("You are an adult.");
}
Output:
The statement inside the if block executes because:
is true.
Understanding Boolean Conditions
An if statement requires a boolean condition.
A condition evaluates to either:
or:
Example:
System.out.println(number > 5);
Output:
You can use that expression directly:
System.out.println("Number is greater than 5.");
}
The if-else Statement
The if-else statement provides two possible paths.
Syntax:
// true block
} else {
// false block
}
Example:
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
Output:
If the condition is true, Java executes the if block.
If it is false, Java executes the else block.
Practical Example – Even or Odd
The modulus operator can be combined with if-else.
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
Output:
Why?
Therefore, the number is odd.
Taking User Input with if-else
Let's make the previous example interactive.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
input.close();
}
}
Example:
Even number
The else-if Statement
When you need to check multiple conditions, use else-if.
Syntax:
// code
} else if (condition2) {
// code
} else if (condition3) {
// code
} else {
// default code
}
Java evaluates the conditions from top to bottom.
As soon as it finds a true condition, it executes that block and skips the remaining branches.
Example – Student Grade
if (marks >= 80) {
System.out.println("Grade A+");
} else if (marks >= 70) {
System.out.println("Grade A");
} else if (marks >= 60) {
System.out.println("Grade B");
} else if (marks >= 50) {
System.out.println("Grade C");
} else if (marks >= 40) {
System.out.println("Grade D");
} else {
System.out.println("Grade F");
}
Output:
The order is important.
For example, if you checked marks >= 40 first, a mark of 75 would match that condition and the more specific conditions would never be reached.
Practical Grade Calculator
Let's create a complete interactive program.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your marks: ");
double marks = input.nextDouble();
if (marks < 0 || marks > 100) {
System.out.println("Invalid marks.");
} else if (marks >= 80) {
System.out.println("Grade: A+");
} else if (marks >= 70) {
System.out.println("Grade: A");
} else if (marks >= 60) {
System.out.println("Grade: B");
} else if (marks >= 50) {
System.out.println("Grade: C");
} else if (marks >= 40) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
input.close();
}
}
This example also demonstrates input validation.
Nested if Statements
An if statement can be placed inside another if statement.
This is called a nested if.
Example:
boolean citizen = true;
if (age >= 18) {
if (citizen) {
System.out.println("Eligible.");
}
}
The inner condition is checked only if the outer condition is true.
Nested if Example – Login
String password = "1234";
if (username.equals("admin")) {
if (password.equals("1234")) {
System.out.println("Login successful.");
} else {
System.out.println("Incorrect password.");
}
} else {
System.out.println("Unknown username.");
}
Output:
For real applications, passwords should not be hard-coded or stored as plain text. This example is only for learning conditional logic.
Combining Conditions with &&
The logical AND operator requires both conditions to be true.
Example:
boolean citizen = true;
if (age >= 18 && citizen) {
System.out.println("Eligible.");
}
Both conditions must be true.
and:
Combining Conditions with ||
The logical OR operator requires at least one condition to be true.
Example:
boolean hasPhone = true;
if (hasEmail || hasPhone) {
System.out.println("Contact information available.");
}
Because hasPhone is true, the complete condition is true.
Using the NOT Operator !
The ! operator reverses a boolean value.
Example:
if (!loggedIn) {
System.out.println("Please log in.");
}
Output:
Multiple Conditions
You can combine several logical operators.
Example:
double income = 50000;
if (age >= 18 && income >= 30000) {
System.out.println("Condition satisfied.");
}
Another example:
boolean guardianPresent = true;
if (age >= 18 || guardianPresent) {
System.out.println("Allowed.");
}
Use parentheses when they make a complex condition easier to understand.
Range Checking
Conditional statements are commonly used to check whether a value falls within a range.
Example:
if (temperature >= 20 && temperature <= 35) {
System.out.println("Temperature is in the normal range.");
}
This means:
AND
Positive, Negative, or Zero
Here's another useful example.
if (number > 0) {
System.out.println("Positive");
} else if (number < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
Output:
Finding the Largest of Two Numbers
int b = 80;
System.out.println("A is larger.");
} else if (b > a) {
System.out.println("B is larger.");
} else {
System.out.println("Both numbers are equal.");
}
Output:
Finding the Largest of Three Numbers
int b = 80;
int c = 70;
System.out.println("A is the largest.");
} else if (b >= a && b >= c) {
System.out.println("B is the largest.");
} else {
System.out.println("C is the largest.");
}
Output:
Ternary Operator
For a simple two-way decision, Java provides the ternary operator.
Syntax:
Example:
String status = age >= 18 ? "Adult" : "Minor";
System.out.println(status);
Output:
This is useful when the decision is simple.
For complex logic, regular if-else statements are generally easier to read.
What Is the switch Statement?
The switch statement is useful when you want to compare one expression against multiple possible values.
For example, a menu might contain:
- 1. Add
- 2. Subtract
- 3. Multiply
- 4. Exit
A switch can select the appropriate action based on the user's choice.
Traditional switch Syntax
Basic syntax:
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Simple switch Example
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day.");
}
Output:
Why Use break?
In a traditional switch, break prevents execution from continuing into the next case.
Example:
switch (number) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
default:
System.out.println("Other");
}
Once case 1 executes, break exits the switch.
What Happens Without break?
Consider:
switch (number) {
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
default:
System.out.println("Other");
}
Traditional switch statements can fall through from one case to subsequent cases when break is omitted.
Output:
Two
Other
This behavior can sometimes be useful, but accidental fall-through is a common beginner mistake.
The default Case
The default case runs when none of the cases match.
Example:
switch (option) {
case 1:
System.out.println("Add");
break;
case 2:
System.out.println("Edit");
break;
case 3:
System.out.println("Delete");
break;
default:
System.out.println("Invalid option.");
}
Output:
Switch with User Input
Let's create a menu program.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("===== MENU =====");
System.out.println("1. Java");
System.out.println("2. Python");
System.out.println("3. C");
System.out.println("4. JavaScript");
System.out.print("Choose a language: ");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("You selected Java.");
break;
case 2:
System.out.println("You selected Python.");
break;
case 3:
System.out.println("You selected C.");
break;
case 4:
System.out.println("You selected JavaScript.");
break;
default:
System.out.println("Invalid choice.");
}
input.close();
}
}
Multiple Cases
You can combine multiple case labels when several values should perform the same action.
Traditional style:
switch (day) {
case 6:
case 7:
System.out.println("Weekend");
break;
default:
}
Output:
Switch with String
Java allows switch with String values.
Example:
switch (language) {
case "Java":
System.out.println("You selected Java.");
break;
case "Python":
System.out.println("You selected Python.");
break;
case "C":
System.out.println("You selected C.");
break;
default:
System.out.println("Unknown language.");
}
Output:
String matching in a switch is based on the String's content.
Modern Switch Syntax
Modern Java also supports a more concise switch statement using arrow labels.
Example:
switch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
case 3 -> System.out.println("Wednesday");
case 4 -> System.out.println("Thursday");
case 5 -> System.out.println("Friday");
case 6, 7 -> System.out.println("Weekend");
default -> System.out.println("Invalid day");
}
This style does not require break after each arrow case.
It is often easier to read and avoids traditional fall-through.
Switch Expressions
Modern Java also supports switch expressions that produce a value.
Example:
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Invalid day";
};
System.out.println(name);
Output:
Using yield in Switch Expressions
If a switch expression needs multiple statements in a case, use a block and yield.
Example:
String grade = switch (marks / 10) {
case 10, 9, 8 -> "A";
case 7 -> {
String result = "B";
yield result;
}
case 6 -> "C";
default -> "F";
};
System.out.println(grade);
yield provides the value produced by that switch branch.
if-else vs switch
Both can be used for decision-making, but they are suited to different situations.
Use if-else when:
- Conditions involve ranges.
- You need complex boolean expressions.
- You compare different variables.
- Conditions are not simply based on one expression's discrete values.
Example:
...
} else if (marks >= 60) {
...
}
Use switch when:
- One expression is being matched against several possible values.
- Menu choices are involved.
- You have fixed options.
Example:
case 1 -> ...
case 2 -> ...
}
Practical Program
1. Age Category
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = input.nextInt();
if (age < 0) {
System.out.println("Invalid age.");
} else if (age <= 12) {
System.out.println("Child");
} else if (age <= 19) {
System.out.println("Teenager");
} else if (age <= 59) {
System.out.println("Adult");
} else {
System.out.println("Senior");
}
input.close();
}
}
2. Login Validation
For educational purposes, you can practice simple credential checking like this:
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Username: ");
String username = input.nextLine();
System.out.print("Password: ");
String password = input.nextLine();
if (username.equals("admin") && password.equals("java123")) {
System.out.println("Login successful.");
} else {
System.out.println("Invalid username or password.");
}
input.close();
}
}
This demonstrates:
- String
- equals()
- &&
- if-else
- User input
3. Electricity Bill
Let's create a simple electricity billing example.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter units consumed: ");
double units = input.nextDouble();
double bill;
if (units < 0) {
System.out.println("Invalid units.");
} else if (units <= 100) {
bill = units * 5;
System.out.printf("Bill: %.2f%n", bill);
} else if (units <= 300) {
bill = 100 * 5 + (units - 100) * 7;
System.out.printf("Bill: %.2f%n", bill);
} else {
bill = 100 * 5 + 200 * 7 + (units - 300) * 10;
System.out.printf("Bill: %.2f%n", bill);
}
input.close();
}
}
This example demonstrates conditional ranges and different calculations for different ranges.
4. Simple Calculator with Switch
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
double a = input.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
char operator = input.next().charAt(0);
System.out.print("Enter second number: ");
double b = input.nextDouble();
switch (operator) {
case '+':
System.out.println("Result: " + (a + b));
break;
case '-':
System.out.println("Result: " + (a - b));
break;
case '*':
System.out.println("Result: " + (a * b));
break;
case '/':
if (b != 0) {
System.out.println("Result: " + (a / b));
} else {
System.out.println("Cannot divide by zero.");
}
break;
default:
System.out.println("Invalid operator.");
}
input.close();
}
}
5. Leap Year
A common programming exercise is determining whether a year is a leap year.
A year is a leap year when:
- It is divisible by 400, or
- It is divisible by 4 but not divisible by 100.
Java program:
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter year: ");
int year = input.nextInt();
if (year % 400 == 0 ||
(year % 4 == 0 && year % 100 != 0)) {
System.out.println("Leap year.");
} else {
System.out.println("Not a leap year.");
}
input.close();
}
}
6. Discount Calculator
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter purchase amount: ");
double amount = input.nextDouble();
double discount;
if (amount >= 10000) {
discount = 20;
} else if (amount >= 5000) {
discount = 10;
} else if (amount >= 2000) {
discount = 5;
} else {
discount = 0;
}
double discountAmount = amount * discount / 100;
double finalAmount = amount - discountAmount;
System.out.printf("Discount: %.2f%%%n", discount);
System.out.printf("Discount Amount: %.2f%n", discountAmount);
System.out.printf("Final Amount: %.2f%n", finalAmount);
input.close();
}
}
Nested Conditional Example
Let's combine multiple conditions.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter marks: ");
double marks = input.nextDouble();
if (marks >= 40) {
System.out.println("You passed.");
if (marks >= 80) {
System.out.println("Excellent performance.");
}
} else {
System.out.println("You failed.");
}
input.close();
}
}
Avoiding Deeply Nested Conditions
Although nested if statements are sometimes useful, excessive nesting can make code difficult to understand.
For example, instead of creating many levels of nested conditions, you can sometimes combine conditions using && and ||.
Less readable:
if (age >= 18) {
if (verified) {
System.out.println("Allowed");
}
}
}
A simpler alternative can be:
System.out.println("Allowed");
}
Choose the structure that makes the logic easiest to understand.
Common Mistake
1. Assignment Instead of Comparison
Beginners sometimes confuse:
with:
Assignment:
Comparison:
System.out.println("Ten");
}
Remember:
== → equality comparison
2. Incorrect Condition Order
Consider:
System.out.println("D");
} else if (marks >= 80) {
System.out.println("A+");
}
A mark of 90 will match marks >= 40 first.
Therefore, the later condition will never be reached for that value.
Better:
System.out.println("A+");
} else if (marks >= 40) {
System.out.println("D");
}
Always consider the order of conditions in an else-if ladder.
3. Missing Braces
Although Java allows certain single statements without braces:
System.out.println("Adult");
using braces is generally clearer:
if (age >= 18) {
System.out.println("Adult");
}
Braces reduce the chance of accidentally associating statements with the wrong condition when code grows.
4. Comparing Strings Incorrectly
Avoid using:
...
}
when your goal is to compare String content.
Prefer:
...
}
You can also write:
...
}
which can be useful when name might be null.
5. Missing break in Traditional Switch
Consider:
case 1:
System.out.println("Add");
case 2:
System.out.println("Edit");
}
This can cause unintended fall-through.
If you intend only one branch to execute, use:
System.out.println("Add");
break;
Or use modern arrow-style switch syntax where appropriate.
Practice Exercises
Now it's time to practice.
Exercise 1 – Positive, Negative, Zero
Ask the user for a number and display whether it is:
- Positive
- Negative
- Zero
Exercise 2 – Even or Odd
Ask the user for an integer and determine whether it is even or odd.
Exercise 3 – Largest Number
Ask the user for three numbers and find the largest.
Exercise 4 – Student Grade
Ask for marks and display:
70–79 → A
60–69 → B
50–59 → C
40–49 → D
Below 40 → F
Also reject marks below 0 or above 100.
Exercise 5 – Voting Eligibility
Ask the user's age.
Display whether the user meets your chosen legal voting-age threshold.
Exercise 6 – Simple Calculator
Ask for:
- First number
- Operator
- Second number
Use switch to perform:
-
*
/
Handle division by zero.
Exercise 7 – Day of the Week
Ask the user for a number from 1 to 7 and display the corresponding day.
Use switch.
Exercise 8 – Month
Ask the user for a month number from 1 to 12 and display the month name.
Challenge Exercise – ATM Menu
Create an ATM-style program.
Display:
===== ATM MENU =====
- 1. Check Balance
- 2. Deposit
- 3. Withdraw
- 4. Exit
Ask the user to choose an option.
Use switch to perform the appropriate action.
For withdrawal, make sure the requested amount does not exceed the available balance.
Mini Project – Student Result Management
Let's combine everything learned so far.
The program should:
- Ask for student name.
- Ask for marks in three subjects.
- Calculate total.
- Calculate average.
- Validate the marks.
- Determine the grade.
- Determine pass/fail status.
- Display the result.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter student name: ");
String name = input.nextLine();
System.out.print("Enter Java marks: ");
double javaMarks = input.nextDouble();
System.out.print("Enter Programming marks: ");
double programmingMarks = input.nextDouble();
System.out.print("Enter Database marks: ");
double databaseMarks = input.nextDouble();
if (javaMarks < 0 || javaMarks > 100 ||
programmingMarks < 0 || programmingMarks > 100 ||
databaseMarks < 0 || databaseMarks > 100) {
System.out.println("Invalid marks entered.");
} else {
double total =
javaMarks +
programmingMarks +
databaseMarks;
double average = total / 3;
String grade;
if (average >= 80) {
grade = "A+";
} else if (average >= 70) {
grade = "A";
} else if (average >= 60) {
grade = "B";
} else if (average >= 50) {
grade = "C";
} else if (average >= 40) {
grade = "D";
} else {
grade = "F";
}
boolean passed =
javaMarks >= 40 &&
programmingMarks >= 40 &&
databaseMarks >= 40;
System.out.println();
System.out.println("==============================");
System.out.println(" STUDENT RESULT");
System.out.println("==============================");
System.out.println("Name: " + name);
System.out.printf("Total: %.2f%n", total);
System.out.printf("Average: %.2f%n", average);
System.out.println("Grade: " + grade);
System.out.println("Status: " +
(passed ? "Passed" : "Failed"));
System.out.println("==============================");
}
input.close();
}
}
This mini project combines:
- Variables
- Data types
- Operators
- Input
- Output
- if
- else-if
- else
- Logical operators
- Boolean values
- Ternary operator
These are important foundations for the next stage of Java programming.
Quick Revision
Concept Purpose
if Executes code when a condition is true
if-else Selects between two paths
else-if Checks multiple conditions
Nested if Places one condition inside another
&& Requires both conditions to be true
` Requires at least one condition to be true
! Reverses a boolean condition
?: Compact two-way conditional expression
switch Selects among multiple fixed alternatives
case Defines a switch alternative
break Exits a traditional switch
default Handles unmatched switch values
-> Modern switch case syntax
yield Produces a value from a switch expression
Key Takeaways
You should now understand that:
- Conditional statements allow Java programs to make decisions.
- if is used for a single condition.
- if-else provides two possible execution paths.
- else-if handles multiple conditions.
- Nested if allows conditions inside other conditions.
- &&, ||, and ! help create logical expressions.
- The ternary operator is useful for simple two-way decisions.
- switch is useful for selecting among fixed alternatives.
- Traditional switch cases can fall through without break.
- Modern switch syntax can use arrow labels.
- Switch expressions can return values.
- Conditions should be ordered carefully.
- String content should normally be compared with equals().
- Input validation is important when accepting user data.
Conclusion
Java conditional statements are essential building blocks that allow programs to make decisions and execute different actions based on specific conditions. In this tutorial, you learned how to use the if, if-else, else-if ladder, and switch statements to control the flow of a Java program efficiently.
By mastering these decision-making structures, you can create smarter applications that respond dynamically to user input and changing data. Whether you are validating information, handling multiple choices, or implementing complex logic, conditional statements are a fundamental skill every Java programmer must understand.
Keep practicing by writing small programs using different conditions and combinations of if-else and switch statements. As you continue your Java programming journey, these concepts will become the foundation for more advanced topics such as loops, methods, object-oriented programming, and real-world application development.
Next Lesson
Step 5: Java Loops – for, while, do-while and Enhanced for Loop
In the next lesson, you will learn how to repeat code efficiently using:
- for loop
- while loop
- do-while loop
- Enhanced for loop
- Nested loops
- break
- continue
- Loop control
- Practical programs
- Pattern printing
- Exercises
- Mini projects
Loops are one of the most important concepts in programming, so make sure you practice the conditional statement exercises before moving forward.

Post a Comment
Thank You For Visit My Website.
I Will Contact As Soon As Possible.