Java Block Scope and if/else Statements
How Java blocks define variable scope (and why you can't redeclare a variable in a nested block), and how to make decisions with if, if/else and if/else if chains, including the dangling else, braces style, and common pitfalls like a stray semicolon.
kvi5hnuCode Sprout team member9 min readOn this page
Up to now, our programs have run straight from top to bottom. Control flow statements let a program make decisions and repeat work. Java's control flow statements are nearly identical to those of C and C++, with a few differences:
- There is no
goto(althoughgotois a reserved word). Instead, a labeledbreakcan jump out of nested loops. - There is an enhanced
forloop ("for each"), similar to C++'s range-basedforand C#'sforeach. - Conditions must be real
booleanvalues; integers don't count as true or false. switchhas modern forms without fall-through.
This article starts with blocks and the if statement. Loops, switch statements and break/continue follow in the next articles.
Blocks and Scope
A block (or compound statement) is any number of statements enclosed in braces { }. Blocks can be nested. You've been writing them all along: the body of main is a block.
A block defines the scope of the variables declared in it: a local variable exists from its declaration to the end of the block that contains it.
public static void main(String[] args) {
int n = 1;
{
int k = 2;
System.out.println(n + k); // both visible here
} // k ends here
System.out.println(n); // fine
// System.out.println(k); // ERROR: cannot find symbol k
}
No redeclaring in nested blocks
You can't declare a local variable with the same name as another local variable that is still in scope, even in an inner block:
public static void main(String[] args) {
int n = 1;
{
int k = 2;
int n = 3; // ERROR: variable n is already defined in method main
}
}
Separate, non-overlapping blocks may reuse a name, because the first variable no longer exists when the second is declared:
{ int temp = 1; System.out.println(temp); }
{ int temp = 2; System.out.println(temp); } // OK: a different variable
The if Statement
The simplest conditional statement is:
if (condition) statement
The condition must be in parentheses and must be a boolean expression. If it's true, the statement runs; otherwise, it's skipped.
To run several statements when the condition is true, use a block:
if (score >= passMark) {
result = "Pass";
stars = 1;
}
Anywhere Java allows a single statement, you can use a block instead. That's how all control structures get multi-statement bodies.
if / else
An if statement can have an else part that runs when the condition is false:
if (score >= passMark) {
result = "Pass";
stars = 1 + (score - passMark) / 25;
} else {
result = "Retake";
stars = 0;
}
Exactly one of the two blocks runs.
else if chains
To choose among several alternatives, chain conditions with else if. They're tested in order, and the first true one wins:

public class Solution {
public static void main(String[] args) {
int passMark = 50;
int[] scores = {96, 78, 52, 31};
for (int score : scores) {
String result;
int stars;
if (score >= 90) {
result = "Distinction";
stars = 3;
} else if (score >= 75) {
result = "Merit";
stars = 2;
} else if (score >= passMark) {
result = "Pass";
stars = 1;
} else {
result = "Retake";
stars = 0;
}
System.out.println(score + ": " + result + ", stars " + stars);
}
}
}
96: Distinction, stars 3
78: Merit, stars 2
52: Pass, stars 1
31: Retake, stars 0
(The for loop over the array just runs the decision for several sample values; loops and arrays come shortly.)
Order matters. A score of 96 also satisfies >= passMark, but since >= 90 is tested first, that branch wins. If you put the passMark test first, every passing score would come out as "Pass". Test the most specific conditions first.
else if isn't a separate keyword: it's an else whose statement happens to be another if. Formatting it on one line makes the chain read like a list of alternatives.
Definite assignment
Notice that result and stars are declared without initial values. That's fine, because the compiler can prove that every path through the if/else chain assigns them before they are printed. If you removed the final else, the compiler would report variable result might not have been initialized. Java's definite assignment rules turn "forgot a case" bugs into compile errors.
The Dangling else
When if statements are nested without braces, which if does an else belong to?
if (x <= 0) if (x == 0) sign = 0; else sign = -1;
The rule: an else belongs to the closest preceding if that doesn't already have an else. Here, the else belongs to if (x == 0), regardless of indentation. This misleading version means exactly the same thing:
if (x <= 0)
if (x == 0) sign = 0;
else // looks like it belongs to the first if, but it doesn't!
sign = -1;
Braces make the intent explicit:
if (x <= 0) {
if (x == 0) sign = 0; else sign = -1;
}
Common Pitfalls
A stray semicolon:
if (balance < 0); // the semicolon IS the statement: an empty one
{
System.out.println("Overdrawn!"); // always runs
}
The if controls an empty statement, and the block below it always runs. IDEs and javac -Xlint warn about this ("empty statement after if").
Assignment instead of comparison:
int x = 5;
if (x = 0) { ... } // ERROR: incompatible types: int cannot be converted to boolean
In C this compiles (and is a notorious bug). In Java it's a compile error, because the condition must be boolean. The one case that still slips through is a boolean variable: if (done = true) assigns true and is always true. Write if (done) instead of comparing with true.
Comparing strings with ==: use equals, as explained in the strings article: if (answer.equals("yes")).
Floating-point equality: if (total == 0.3) may fail because of rounding. Compare with a tolerance: if (Math.abs(total - 0.3) < 1e-9).
Testing a type and then casting: older code writes if (obj instanceof String) { String s = (String) obj; ... }. Since Java 16, a pattern does both at once, and the variable can be used in the rest of the condition: if (obj instanceof String s && !s.isBlank()). Article 43 explains the scope rules.
if Statement or Conditional Expression?
When both branches simply compute a value for the same variable, the conditional operator ?: (or a switch expression for many cases) is more concise:
String msg;
if (temp > 30) msg = "hot"; else msg = "ok"; // statement form
String msg2 = temp > 30 ? "hot" : "ok"; // expression form
Use the if statement when the branches do different things (call methods, print, update several variables).
Brace Styles
Two layouts are common. Both are fine; follow your project's style and be consistent:
// "K&R" / Egyptian braces: the Java mainstream (Oracle, Google style)
if (ready) {
start();
} else {
waitABit();
}
// Allman style: each brace on its own line
if (ready)
{
start();
}
else
{
waitABit();
}
Your IDE can reformat code to either style automatically (IntelliJ IDEA: Code ▸ Reformat Code).
Common questions
Can a variable declared inside an if block be used after it?
No. Its scope ends at the closing brace. Declare the variable before the if and assign it in every branch, and definite assignment then checks that every path sets it. Often a conditional expression or a switch expression is neater: String label = score >= 50 ? "pass" : "fail";.
Is if (flag == true) wrong?
It works, but it is redundant: if (flag) says the same thing. Comparing with true also invites the if (flag = true) typo, which compiles and is always true. For the negative case, write if (!flag).
Should I use early returns or nested ifs?
Guard clauses at the top of a method (if (input == null) return;) usually read better than deeply nested if/else blocks. They handle the special cases first and leave the main logic unindented. Most modern style guides recommend them.
Does the pattern variable in if (obj instanceof String s) exist in the else branch?
No. s is in scope only where the compiler knows the test succeeded, which is the then branch and the right side of &&. With a negated test, such as if (!(obj instanceof String s)) return;, s is in scope after the if. Article 43 covers these flow-scoping rules.
Can I write if conditions with multiple comparisons, like 1 < x < 5?
No. 1 < x is a boolean, and boolean < int doesn't compile. Write 1 < x && x < 5, which keeps the variable in the middle so the condition still reads like the mathematical notation.
Summary
- A block
{ … }groups statements and defines the scope of local variables declared in it. - Java forbids redeclaring a local variable that's still in scope, even in a nested block. Disjoint blocks may reuse names.
if (condition) statementruns the statement when thebooleancondition is true;elseprovides the alternative.else ifchains test conditions in order; the first true one wins, so put specific conditions first.- An
elsebelongs to the nearest unmatchedif. Use braces to avoid dangling-else confusion. - Watch for stray semicolons after
if (…),=vs==with booleans,==on strings, and exact floating-point comparisons. - The compiler's definite assignment rules ensure that variables are assigned on every path before use.
Practice Questions
What does this print when x = 5? if (x > 0) if (x > 10) System.out.println("big"); else System.out.println("small");
small. The else belongs to the inner if (x > 10). Since x > 0 is true and x > 10 is false, the inner else runs.
Why does this not compile? int n = 0; { int n = 1; }
Java doesn't allow a local variable to be redeclared while another local variable with the same name is in scope. The outer n is still in scope inside the nested block.
A student writes: if (score >= 60) grade = "D"; else if (score >= 70) grade = "C"; else if (score >= 80) grade = "B"; … What's wrong?
The conditions are in the wrong order. Every score ≥ 60 matches the first test, so nobody ever gets C or B. Test from the highest threshold down: >= 90, >= 80, >= 70, >= 60, else.
What is printed? int balance = 50; if (balance < 0); { System.out.println("Overdrawn"); }
Overdrawn. The semicolon after if (balance < 0) is an empty statement that forms the whole if body, so the block after it always runs.
Why does if (count = 0) fail to compile in Java, while if (found = true) compiles?
count = 0 is an int expression, and an if condition must be boolean, so it's a type error. found = true is an assignment whose value is true, a boolean, so it compiles and is always true: a bug. Write if (found).
Previous: Java File Input and Output Basics: Reading and Writing Text Files
Related reading
- The Java String API, Code Points, StringBuilder and Text Blocks
- Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks
- Java CompletableFuture: Asynchronous Programming with Callbacks and Composition
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
- Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.