Beginner · Control flow and methods · topic 6 of 60 · 20 min
Decisions: if, else and the ternary
Explanation
Why decisions?
Programs must react to data: approve a loan only above a credit score, charge a late fee after the due date, show "out of stock" when quantity is zero. An if statement runs code only when its condition is true.
int marks = 72;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 60) {
System.out.println("Grade B");
} else if (marks >= 35) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}Conditions must be boolean
Unlike C or JavaScript, Java does not treat numbers or objects as true/false. if (count) and if (name) do not compile. Write the comparison: if (count > 0), if (name != null). This removes a whole class of bugs.
int x = 3;
// if (x = 5) { } // compile error: incompatible types: int cannot be converted to boolean
if (x == 5) { } // correct comparisonBraces and the dangling else
Without braces, an if controls only the next single statement. An else always belongs to the nearest unmatched if, which can be different from what the indentation suggests. Always use braces, even for one line.
int a = 5, b = -1;
if (a > 0)
if (b > 0)
System.out.println("both positive");
else
System.out.println("a is not positive"); // misleading! this else belongs to if (b > 0)
// Prints "a is not positive" even though a is 5.Combining conditions
int age = 30, cibil = 760;
double salary = 55000;
if (age >= 21 && age <= 60 && cibil >= 750 && salary >= 25000) {
System.out.println("Pre-approved for a personal loan");
}The ternary operator
int items = 1;
String label = items == 1 ? "item" : "items";
System.out.println(items + " " + label); // 1 item
int fee = amount >= 499 ? 0 : 40;Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Decisions: if, else and the ternary · 1/5
In this lesson your Java programs will start making decisions.
Prefer a video by a teacher? Find free videos on “java if else statement ternary operator tutorial” on YouTube ↗
In real life: Electricity slabs
A state electricity board bills in slabs. A billing module chooses the per-unit rate with an if/else-if chain. The rates below are sample values for practice, not a real tariff.
static double ratePerUnit(int units) {
if (units <= 100) return 3.0;
else if (units <= 300) return 5.0;
else return 7.5;
}Practice (0/3 done)
What does this print? int t = 32; if (t > 35) System.out.println("Hot"); else if (t > 25) System.out.println("Warm"); else if (t > 30) System.out.println("Very warm"); else System.out.println("Cool");
Which line has the bug? 1: int stock = 0; 2: if (stock == 0); { 3: System.out.println("Out of stock"); 4: }
Write a method static String grade(int marks) that returns "A" for 90+, "B" for 75–89, "C" for 60–74, "D" for 35–59 and "F" below 35, and "Invalid" for marks below 0 or above 100. Test it from main with at least 6 values including 0, 35, 100 and 101.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- switch statements and switch expressionsControl flow and methods · same module
- Loops: for, while, do-while and for-eachControl flow and methods · same module
- Methods: parameters, return values and overloadingControl flow and methods · same module
- Decisions: if, else, switch and switch expressionsC# and .NET · Decisions, loops and methods
- Decisions: if, else and switchC Programming (from zero to systems) · Operators and control flow
- Operators and decisions: if, else and switchC++ Programming (modern C++ and DSA) · Decisions, loops and functions
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
int n = 4; if (n) { … } What happens?
Answer: Compile error: int cannot be converted to boolean
Java conditions must be boolean.
How many branches of if / else if / else can run?
Answer: At most one
Only the first true branch runs.
What is x after: int x = 10 > 5 ? 1 : 2;
Answer: 1
The condition is true, so the first value is chosen.
boolean ok = false; if (ok = true) print("yes"); What happens?
Answer: Prints yes, because ok is assigned true
Assigning a boolean is a valid condition; this bug compiles. Write if (ok).
A switch case has code but no break. What happens?Related
Answer: Compile error: control cannot fall through
C# does not allow fall-through from a non-empty case (error CS0163).
What happens without break at the end of a case?Related
Answer: Execution falls through to the next case
That is fall-through.
Why does if (x = 0) never run its block?Related
Answer: Because it assigns 0 to x, and 0 counts as false
The assignment gives the value 0, which is false. You probably meant x == 0.
Which Kotlin feature replaces Java's switch statement?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 4 more topics in “Control flow and methods” before its exam: switch statements and switch expressions, Loops: for, while, do-while and for-each, Methods: parameters, return values and overloading, Reading errors and debugging.
- Module 2 exam: Control flow and methods · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Arrays and strings. 60 topics left in the course before the final exam.