Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Basics

Java Scope, Code Blocks and the Call Stack

Braces make rooms: a variable is born at its line and dies at its closing brace. Then the call stack, frame by frame, as main calls orderTotal, discountFor and percent to turn 250 into a bill of 225.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

What you will learn

  • Explain block scope: a variable lives from its line to the closing brace of its block
  • Fix 'cannot find symbol' errors caused by using a variable outside its block
  • Tell when a local may share a name with a static field and when it may not
  • Trace how the call stack pushes and pops a frame for each method call

Before you start

  • Java methods and overloading

Where does a variable live, when does it die, and how does Java keep track when methods call other methods? Two ideas answer all three: block scope and the call stack.

Braces make rooms

Every pair of curly braces is a room: a class, a method, an if block, a loop. A variable declared inside a room is born and dies with it. Think of a house: from the bedroom you can't see how much sugar is left in the kitchen jar.

From an inner room you can see outwards, but not the other way round.

package org.studyeasy.s02l14;

public class Ex01_IfBlockScope {
    static int finalAmount(int count) {
        int subtotal = 250;
        if (count >= 4) {
            int off = subtotal / 10;
            subtotal = subtotal - off;
        }
        return subtotal;
    }

    public static void main(String[] args) {
        System.out.println("4 items: " + finalAmount(4));
        System.out.println("2 items: " + finalAmount(2));
    }
}
4 items: 225
2 items: 250

The if block can use subtotal, because it looks outwards into the method. off is born inside the if and dies at its closing brace. The return line sits outside, so it can't see off. Add System.out.println(off); after the if and javac says "cannot find symbol". The fix: return the value you need, or declare the variable outside the block.

Born at the line, gone at the brace

VariableBornDies
count (parameter)with the callwhen the method returns
subtotalint subtotal = 250;the method's closing brace
offint off = ... inside the ifthe if's closing brace

A loop has its own room

package org.studyeasy.s02l14;

public class Ex02_LoopScope {
    public static void main(String[] args) {
        for (int cup = 1; cup <= 3; cup++) {
            System.out.println("Pouring cup " + cup);
        }
        System.out.println("Done pouring");
    }
}
Pouring cup 1
Pouring cup 2
Pouring cup 3
Done pouring

cup is declared in the loop header, so it belongs to the for block, not to main. Print it after the loop and you get "cannot find symbol" again.

Cheat sheet

KindLives
Method parameterthe whole method, until it returns
Local in a methodits line to the method's closing brace
Local in an if / elseits line to that block's closing brace
for-loop variablethe whole loop
static fieldwith the class, until the program ends

The rule is always the same: find the nearest pair of braces around the declaration.

One name, two places

package org.studyeasy.s02l14;

public class Ex03_Shadowing {
    static int discount = 10;

    public static void main(String[] args) {
        int discount = 20;
        System.out.println("local discount: " + discount);
        System.out.println("class discount: " + Ex03_Shadowing.discount);
    }
}
local discount: 20
class discount: 10

The static field belongs to the class, a house of its own in memory. The local is an apartment inside main. Plain discount means the nearest one, 20. The class name reaches the field: Ex03_Shadowing.discount is still 10. This is called shadowing.

Two locals with the same name are not allowed, though. Add a second int discount = 5; inside main and javac says "variable discount is already defined".

The call stack: push and pop

package org.studyeasy.s02l14;

public class Ex04_CallStack {
    public static void main(String[] args) {
        int bill = orderTotal(250);
        System.out.println("Bill: " + bill);
    }

    static int orderTotal(int subtotal) {
        int off = discountFor(subtotal);
        System.out.println("Discount: " + off);
        return subtotal - off;
    }

    static int discountFor(int subtotal) {
        return percent(subtotal, 10);
    }

    static int percent(int amount, int rate) {
        return amount * rate / 100;
    }
}
Discount: 25
Bill: 225

Java tracks calls with a stack, like a pile of plates. Each call puts a new plate, a frame, on top. The frame holds that call's own parameters and locals.

The call stack at its tallest: main at the bottom with bill not set yet, then orderTotal with subtotal 250, then discountFor with subtotal 250, then percent on top with amount 250 and rate 10. percent returns 25 and pops first; discountFor returns 25; orderTotal returns 225 and bill becomes 225. percentamount 250, rate 10 discountForsubtotal 250 orderTotalsubtotal 250, off ? mainbill ? returns 25, pops first returns 25: off = 25 returns 225: bill = 225
Four frames at the tallest point. The top frame finishes first and hands its answer to the frame below.
  1. main starts, so its frame is pushed. bill has no value yet.
  2. main calls orderTotal(250): a new frame with subtotal 250.
  3. orderTotal calls discountFor, which calls percent(250, 10). Four frames now, percent on top.
  4. percent works out 250 x 10 / 100 = 25. Its frame pops and 25 goes down; discountFor returns it too, so off becomes 25 and "Discount: 25" prints.
  5. orderTotal returns 250 - 25 = 225 and pops. bill is 225, "Bill: 225" prints, and when main ends the stack is empty.

Make percent call itself (return percent(amount, rate);) and frames pile up until the program stops with StackOverflowError. You'll also see these frames in IntelliJ's debugger, covered in debugging in IntelliJ.

Recap

  • Every pair of braces is a room. An inner room sees outwards, never inwards.
  • A variable lives from its declaration to the closing brace of its block.
  • "cannot find symbol" often means you used a variable outside its room.
  • A local can shadow a static field; two locals can't share a name.
  • Each call pushes a frame; the top one finishes first and passes its answer down.

Keep going in Java · 17 of 79

Previous
Java Methods and Overloading: Parameters, return and Pass-by-Value
Next post
Read User Input in Java with Scanner (and the Leftover Enter Trap)
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program

Install JDK 25 (Microsoft Build of OpenJDK) with JAVA_HOME, install IntelliJ IDEA, then point a run configuration at the JDK and the main class and run Hello World.

Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA

Open IntelliJ's AI Chat, pick Claude Agent (the agent behind Claude Code) or Copilot and a model, ask in plain words for Main.java to print the date and time, review the change, and run it.

Java Hello World with Maven: What the JDK Does and What Maven Adds

javac compiles HelloWorld.java into bytecode and java runs it on the JVM. Maven adds one pom.xml, the same folders in every project and one build command. Then a real Maven Hello World in IntelliJ.

Java Variables, Keywords and Naming Rules

A variable is a labelled jar that holds one value at a time. Four small programs show declaring, reassigning, the names Java accepts, the keywords it reserves, and why daysUntilLaunch beats d.

On this page

  • Braces make rooms
  • Born at the line, gone at the brace
  • A loop has its own room
  • Cheat sheet
  • One name, two places
  • The call stack: push and pop
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.