A while loop in Java repeats a block of code as long as a condition stays true. You write the keyword while, put a boolean expression in parentheses, then wrap your statements in curly braces. The loop checks the condition before each iteration, so if the condition is false from the start, the body never runs. That single behaviour difference is what separates it from a do-while loop.
- Key Takeaway 1: Java uses
if,else ifandelsefor branching. There is noelifkeyword; that belongs to Python. - Key Takeaway 2: The while loop in Java checks its condition before execution; do-while checks after, guaranteeing at least one run.
- Key Takeaway 3: Java 12 introduced switch expressions that return a value and use arrow syntax, cutting boilerplate dramatically.
- Key Takeaway 4: A
forloop is best when you know the iteration count; awhileloop is best when you don’t. - Key Takeaway 5: Unhandled infinite loops and missing
breakstatements in switch are two of the most common beginner bugs, so read about Java exceptions and common runtime errors once you finish this page.
if and else-if in Java
The if statement is the most fundamental decision point in any Java program. You give it a boolean expression; if that expression is true, the block executes. If it’s false, Java skips it entirely and moves on.
Here’s a realistic java if statement example you’d actually write in a student grade-checker:
int marks = 72;
if (marks >= 75) {
System.out.println("Distinction");
} else if (marks >= 60) {
System.out.println("First Class");
} else if (marks >= 45) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
That prints “First Class”. Notice the chain: if, then as many else if blocks as you need, then an optional else at the end.
Does Java have elif?
No. If you’re coming from Python, you’ll miss elif, but Java’s equivalent is simply else if written as two words. The behaviour is identical: Java evaluates each condition in order and executes the first block that matches. Every else if in Java is just a shorthand for nesting another if inside an else block.
Common mistakes with if statements
One practical mistake is using = (assignment) instead of == (comparison) inside an if condition. In Java, the compiler will actually catch this when you try to compare primitive types, but it’s still worth being deliberate. Another common error is forgetting curly braces on single-statement blocks; the code looks fine but behaves unexpectedly the moment you add a second line.
switch and the New switch Expressions
The classic switch statement matches a variable against a series of case values. It’s cleaner than a long else if chain when you’re testing one variable against many possible discrete values, like a day of the week or a menu option.
Traditional switch case example
Here’s a java switch case example that maps an integer day number to a name:
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("Other day");
}
The break statement is critical. Without it, execution “falls through” into the next case. That’s not a bug in the language; it’s a feature some developers use intentionally, but it bites beginners constantly. Every professional Java developer has debugged a missing break at least once.
Java 12 switch expressions
Java 12 introduced switch expressions as a preview feature, and they became standard in Java 14. This is the java 12 switch change most developers care about. The new arrow syntax eliminates fall-through entirely and lets the switch return a value directly.
The same example rewritten with the modern syntax:
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Other day";
};
System.out.println(dayName);
No break needed. Each arm uses -> and the whole expression yields a value you can assign to a variable. According to the OpenJDK JEP 361, the goal was explicitly to reduce “the verbosity of switch statements” and eliminate the error-prone fall-through default. If you’re on a modern JDK (17 LTS or 21 LTS), use this syntax by default.
| Feature | Traditional switch | Java 12+ switch expression |
|---|---|---|
| Fall-through | Yes (requires break) | No (arrow syntax) |
| Returns a value | No | Yes |
| Syntax | case X: … break; | case X -> value; |
| Exhaustiveness check | No | Yes (compiler error if default missing) |
| Available from | Java 1.0 | Java 14 (standard) |
for Loops
The for loop is your go-to when you know exactly how many times you want to iterate. The java for syntax packs three things into one line: initialisation, condition and update.
Basic for loop syntax and example
Structure: for (initialisation; condition; update) { body }. A simple java for loop example that prints numbers 1 to 5:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
The initialisation (int i = 1) runs once. The condition (i <= 5) is checked before every iteration. The update (i++) runs after every iteration. If the condition is false on the very first check, the body never executes, just like a while loop.
Enhanced for loop (for-each)
Java also gives you a for-each loop for iterating over arrays and collections without managing an index:
String[] cities = {"Delhi", "Mumbai", "Bengaluru"};
for (String city : cities) {
System.out.println(city);
}
This is cleaner and less error-prone than a standard index loop when you don't need the index value itself. The trade-off is that you can't easily skip elements or iterate backwards.
break and continue
break exits the loop immediately. continue skips the rest of the current iteration and jumps to the next check. Both work in for and while loops. Use them sparingly; overusing them makes loop logic hard to follow during code reviews.
while and do-while Loops
The while loop in Java is the simplest loop structure. You use it when the number of iterations depends on a condition that changes during execution, not on a counter you set upfront.
while syntax in Java
The while syntax in Java is: while (condition) { body }. Here's a while program in Java that reads user input until a valid score is entered:
int score = -1;
while (score < 0 || score > 100) {
System.out.print("Enter score (0-100): ");
score = scanner.nextInt();
}
System.out.println("Valid score: " + score);
The loop keeps running until the user enters a number between 0 and 100. That's the natural use case: you don't know how many attempts the user will need.
do-while loop
The do-while loop is the less-common sibling. It guarantees the body runs at least once because the condition is checked after the body, not before:
int attempt = 0;
do {
System.out.println("Attempt: " + attempt);
attempt++;
} while (attempt < 3);
This prints "Attempt: 0", "Attempt: 1", "Attempt: 2". Even if attempt started at 3, the body would still run once. That makes do-while perfect for menu-driven programs where you always want to show the menu at least once before checking if the user wants to exit.
Avoiding infinite loops
The most common bug with while loops is forgetting to update the variable that the condition depends on. If score never changes inside the loop body, the condition never becomes false and your program hangs. In a production environment, an infinite loop in a server thread can consume 100% CPU and bring down the whole service. Always double-check that your loop variable is actually being modified.
According to the Stack Overflow Developer Survey 2024, Java remains one of the top five most-used languages among professional developers globally, which means solid control-flow fundamentals are genuinely tested in interviews at companies like TCS, Infosys, Wipro and product startups alike. If you're preparing for placements after a BSc Computer Science or considering the career trajectory covered in our guide to jobs and salary after MCA, loops and conditionals will come up in every technical round.
The TIOBE Index (April 2025) ranks Java at position 4 among the world's most popular programming languages, behind Python, C and C++. That ranking has been consistent for over two decades, which is why so many software development tools are built around Java toolchains and why interviewers still test these fundamentals hard.
If you're also learning other languages, the mental model transfers directly. Python's while and for loops work on the same principles; see our guide on how to write and run a Python program to compare the syntax side by side. C does the same, and you can check how to write, compile and run a C program for a low-level perspective on why loop constructs exist at all.
Frequently Asked Questions
How do I write a while loop in Java?
Write while (condition) { } where condition is any boolean expression. The loop checks the condition before each iteration and keeps running as long as it's true. Always make sure something inside the loop body eventually makes the condition false, or you'll create an infinite loop.
What is the syntax of a for loop in Java?
The java for syntax is for (init; condition; update) { body }. The initialisation runs once at the start, the condition is checked before each iteration, and the update runs after each iteration. For example, for (int i = 0; i < 10; i++) iterates ten times with i going from 0 to 9.
Does Java have elif?
No, Java doesn't have an elif keyword. That's Python syntax. In Java you write else if as two separate words. The behaviour is identical: Java evaluates each condition in order and executes the first matching block, ignoring the rest.
What changed in the Java 12 switch?
Java 12 previewed switch expressions, which became standard in Java 14. The key changes are arrow syntax (case X -> instead of case X:), no fall-through by default, and the ability to return a value directly from the switch. This eliminates the need for break and makes the code significantly shorter and safer.
How do I use switch case in Java?
Write switch (variable) { case value: ... break; default: ... }. Match the variable against each case value; when a match is found, that block runs. Always include break at the end of each case in the traditional syntax, or use the Java 14+ arrow syntax to avoid fall-through entirely.
Now you have the full picture of Java control flow. The while loop in Java, the for loop, if-else-if chains and switch expressions are the four building blocks every Java program is built from. Master these and every other Java concept becomes easier to read and reason about.
- This week: Write five small programs in Java, one for each construct covered here: a grade checker with if/else-if, a day-name switch using both traditional and arrow syntax, a countdown for loop, a user-input while loop, and a menu do-while loop.
- Next: Read the guide on Java exceptions and common runtime errors so you know what happens when your loops or conditions hit unexpected input.
- Build on it: Strong programming fundamentals are the foundation for ethical hacking, secure coding, AI and blockchain development. If you're serious about a career in tech security or AI, explore the CEH v13 AI online course at 3.0 University or browse the full 3.0 University certification catalogue to find the right next step.
Last updated: November 2026. Reviewed by the 3University editorial team.