Static Members (Variables, Methods, Blocks) & Final Variables
1. Topic Introduction
Most variables and methods belong to individual objects (s1.name, s2.name). But sometimes a property—like a shared college name, a total object counter, or mathematical PI—belongs to the entire class or must never change. Java handles class-level sharing with static and immutability of constants with final.
static) vs Engraved Plaque (final)Every student in a classroom has their own personal notebook (instance variable). But the **Classroom Whiteboard (static variable) has only ONE shared copy in the room—if one student writes 'Exam Friday' on the whiteboard, everyone sees 'Exam Friday'! A static block** is the teacher writing the date on that whiteboard BEFORE any student walks into class (main). Meanwhile, a **final variable** is a number engraved in brass (MAX_MARKS = 60)—you can assign it once, and no one can erase or alter it afterwards!
static = 1 shared class-level copy loaded once in Method Area (usable without new; cannot use this/super). final variable = constant assignable only once.3. Essential Exam Definitions
static outside methods; allocated once in the Method Area at class-loading time and shared across all instances of the class.static that belongs to the class itself (ClassName.method()), callable without creating an object. Cannot access non-static members directly or use this/super.static { ... } initializer block executed automatically once when the class is first loaded into JVM memory—prior to main() and any object creation.final whose value cannot be reassigned once initialized (Java's named constant). Combined with static, forms a class constant (static final).4. Detailed Technical Explanation & Syntax
Restrictions on static Methods (Classic Exam Question!)
Because a static method can run before ANY object exists, Java enforces strict rules inside static methods:
- 1. They can directly access ONLY other
staticvariables andstaticmethods. - 2. They CANNOT directly access non-static (instance) variables or call non-static methods without creating/receiving an object reference (
obj.instanceVar). - 3. They CANNOT refer to
thisorsuperin any way.
Static Initialization Order (UseStatic Trace)
When a class is loaded by the JVM: (1) all static variable declarations are allocated & initialized in textual order -> (2) static { ... } blocks execute in top-down order -> (3) main() begins execution.
Final Variables & Blank Final Variables
A final variable can be assigned ONLY once. If not initialized at declaration (final int ROLL_NO;), it is a blank final variable and MUST be initialized in EVERY constructor (or instance initializer block). A final reference variable (final StringBuilder sb) cannot be reassigned to point to a new object (sb = ... illegal), though the object's internal state can still mutate unless the object itself is immutable.
5. Working Principle: Class Loading Sequence for Static Members
- 1. JVM ClassLoader loads
.classinto Method Area. - 2.
static int a = 3;runs ->staticblock initializesb = a * 4(12). - 3.
main()executes and seesa = 3, b = 12already ready.
7. Complete Java Code Examples & Tracing
UseStatic execution sequence from lecture notes combined with object-counting static field and final constants.| 1 | public class UseStaticAndFinalDemo { |
| 2 | static int a = 3; |
| 3 | static int b; |
| 4 | static final int MAX_ATTEMPTS = 3; // Class constant |
| 5 | final int studentId; // Blank final initialized per object |
| 6 | |
| 7 | // Static initializer block: runs ONCE when class loads |
| 8 | static { |
| 9 | System.out.println("1. Static block initialized."); |
| 10 | b = a * 4; |
| 11 | } |
| 12 | |
| 13 | UseStaticAndFinalDemo(int id) { |
| 14 | this.studentId = id; // Valid: blank final assigned once in constructor |
| 15 | } |
| 16 | |
| 17 | static void showStatic(int x) { |
| 18 | System.out.println("x = " + x + ", a = " + a + ", b = " + b); |
| 19 | // System.out.println(studentId); // COMPILE ERROR: non-static from static! |
| 20 | } |
| 21 | |
| 22 | public static void main(String[] args) { |
| 23 | System.out.println("2. main() running. Max attempts = " + MAX_ATTEMPTS); |
| 24 | showStatic(42); |
| 25 | UseStaticAndFinalDemo u1 = new UseStaticAndFinalDemo(101); |
| 26 | System.out.println("Object studentId (final): " + u1.studentId); |
| 27 | } |
| 28 | } |
1. Static block initialized. 2. main() running. Max attempts = 3 x = 42, a = 3, b = 12 Object studentId (final): 101
staticfinalthisvoid- Trying to read an instance field directly inside
main()without creating an object (non-static variable cannot be referenced from a static context). - Reassigning a
finalvariable (MAX_ATTEMPTS = 5;-> compile error). - Trying to declare a local variable inside a method as
static(illegal in Java!).
Real-World Applications
- Utility classes like
java.lang.Math(Math.PI,Math.sqrt()) consist purely ofstatic finalconstants andstaticmethods. - Object counters or shared database configuration pools rely on
staticfields.
Important KTU Exam Points
- Memorize the 3 restrictions on
staticmethods (no non-static direct access,no this,no super). - Trace
staticblock execution order accurately: static blocks ALWAYS execute BEFOREmain()!
Memory Techniques & Revision
- Static Restrictions — 'N-T-S': No Non-static direct access, No
this, Nosuper.
Common Pitfalls to Avoid
- Writing
static int x = 0;inside a method—staticis allowed ONLY at class level (not on local variables).
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: The static modifier binds class members to the class itself rather than to individual object instances, optimizing memory in the Method Area.
- Static Variable: Single copy created once during class loading and shared by all objects (
ClassName.var). - Static Method: Invoked via class name without
new; restricted from directly accessing instance fields/methods or usingthis/super. - Static Block:
static { ... }runs automatically once when the class loads (beforemain()), ideal for complex static setup.
| class Counter { |
| static int count = 0; |
| static { System.out.println("Loaded"); } |
| Counter() { count++; } |
| } |
Quick Understanding Check
1. When does a static { ... } block execute in a class containing main()?