Java Conditional Expressions – Easy Guide
Conditions help Java programs make decisions. These allow Java to choose different execution paths depending on values or states at runtime.
1. Introduction
Java decision-making statements allow programs to behave differently under different conditions. They control program flow based on boolean expressions (true/false).
The main conditional expressions are: if, nested if, if–else, and the ternary operator.
2. The if Expression
if checks a condition, and if it's true, executes a block of statements.
int marks = 85;
if(marks > 50){
System.out.println("Pass");
}
Pass
3. Nested if Expressions
You can put one if inside another. Useful for multi-level decisions.
int marks = 90;
if(marks > 50){
if(marks > 80){
System.out.println("Distinction");
}
}
Distinction
4. if–else Expression
When condition is true → execute block A, else → execute block B.
int age = 16;
if(age >= 18){
System.out.println("Eligible to Vote");
}else{
System.out.println("Not Eligible");
}
Not Eligible
5. Ternary Operator (?:)
Ternary is a compact form of if–else. Syntax: condition ? value1 : value2.
int num = 7;
String res = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(res);
Odd
6. The switch Statement
The switch statement allows multi-way branching based on the value of an expression. It is clearer than writing multiple if–else-if chains.
It compares a value against multiple case labels and executes the matching block.
int day = 3;
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");
}
Wednesday
Practice Questions – Click to Reveal Answers
1️⃣ What is the purpose of an if statement?
To execute code only when a condition is true.
2️⃣ What is a nested if?
An if statement written inside another if statement.
3️⃣ Write syntax of if–else.
if(condition){ }
else { }
4️⃣ What does the ternary operator return?
One of two values based on the condition.
5️⃣ What is the output of: (5 > 3 ? "Yes" : "No")?
Yes
Quick Summary
- If statements check conditions.
- Nested if allows multi-level checking.
- If–else handles two-way decisions.
- Ternary is a short version of if–else.
- These concepts are the foundation of decision-making in Java.