Java OOP
Static Members
Complete lesson for Static Members using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Static Members
Section: Java OOP. static variables, static methods, static blocks, and static nested classes — members that belong to the class, not to each object.
What is the static keyword?
staticmarks a member that belongs to the class itself, not to any one object.- A static member is created once, when the class is loaded and initialized. All objects share it, and it is usable even when zero objects exist.
- Access it with the class name:
ClassName.member. - Real life: the school name painted on the school gate is one for all students, but every student has a different roll number. School name = static, roll number = instance.
- Java allows static on four kinds of members (variables, methods, blocks, nested classes) plus static imports.
| Place | Allowed? | Example | Meaning |
|---|---|---|---|
| Variable (field) | Yes | static int count; | One copy shared by all objects |
| Method | Yes | static int square(int x) | Called without creating an object |
| Block | Yes | static { ... } | Runs once when the class is initialized |
| Nested class | Yes | static class Node { } | Nested type with no link to an outer object |
| Import | Yes | import static java.lang.Math.PI; | Use static members without the class name |
| Top-level class | No | static class A { } at file level | Compile error: modifier static not allowed here |
| Local variable | No | static int x = 0; inside a method | Compile error: illegal start of expression |
| Constructor | No | static Student() { } | A constructor always builds an object |
public class School {
static String schoolName = "LearnCodeGuru Public School"; // one copy for all
int rollNo; // one per object
String name; // one per object
School(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
void show() {
System.out.println(rollNo + " " + name + " - " + schoolName);
}
public static void main(String[] args) {
School s1 = new School(1, "Asha");
School s2 = new School(2, "Ravi");
s1.show();
s2.show();
School.schoolName = "LCG International School"; // change it once
s1.show(); // both objects
s2.show(); // see the new name
}
} Static variable (class variable)
- Declared with
staticinside the class but outside every method. Syntax:access static type name = value;for exampleprivate static int count = 0;. - Memory is allocated once, when the class is initialized, not every time you call
new. - Gets a default value like instance fields:
0,0.0,false, ornull. - Every object reads and writes the same copy, so a change made through one object is seen by all objects.
- Common uses: object counters, ID generators, shared settings (interest rate, tax rate), constants with
static final, and caches. - Also called a class variable. An instance variable is also called an object variable or non-static field.
public class Visitor {
private static int totalVisitors = 0; // shared by every Visitor
private final String name; // different for each Visitor
Visitor(String name) {
this.name = name;
totalVisitors++;
}
static int getTotalVisitors() {
return totalVisitors;
}
public static void main(String[] args) {
System.out.println("Before: " + Visitor.getTotalVisitors()); // 0
new Visitor("Asha");
new Visitor("Ravi");
new Visitor("Kiran");
System.out.println("After: " + Visitor.getTotalVisitors()); // 3
}
} Real-life examples of static variables
- Ask: is this value the same for every object? If yes, it can be static. If it changes per object, it must be an instance variable.
| Real-life situation | Static (one value shared by all) | Instance (different for each object) |
|---|---|---|
| College students | College name, college code | Student name, roll number, marks |
| Bank accounts | Interest rate, bank name, IFSC prefix | Account number, holder name, balance |
| Company employees | Company name, office address | Employee id, name, salary |
| Cricket team | Team name, total team score | Player name, runs, wickets |
| Website users | Total visitors count | User name, login time |
| Train passengers | Train number, route | Passenger name, seat number |
| Circles in geometry | PI = 3.14159 | Radius of each circle |
| Products in a shop | GST rate | Product name, price, stock |
| Mobile app users | App version, server URL | Theme, language, notification settings |
| Hostel rooms | Hostel name, warden phone number | Room number, occupant names |
public class SavingsAccount {
static double interestRate = 4.0; // percent, same for every account
private final String holder;
private final double balance;
SavingsAccount(String holder, double balance) {
this.holder = holder;
this.balance = balance;
}
double yearlyInterest() {
return balance * interestRate / 100;
}
public static void main(String[] args) {
SavingsAccount a = new SavingsAccount("Asha", 10000);
SavingsAccount b = new SavingsAccount("Ravi", 50000);
System.out.println(a.holder + ": " + a.yearlyInterest()); // 400.0
System.out.println(b.holder + ": " + b.yearlyInterest()); // 2000.0
SavingsAccount.interestRate = 5.0; // bank changes the rate once
System.out.println(a.holder + ": " + a.yearlyInterest()); // 500.0
System.out.println(b.holder + ": " + b.yearlyInterest()); // 2500.0
}
} Differences between instance variable and static variable
- The key difference: one copy per object (instance) versus one copy per class (static).
| Point | Instance variable | Static variable |
|---|---|---|
| Keyword | No keyword | static |
| Belongs to | Each object | The class |
| Number of copies | One per object | One per class |
| Memory allocated | When an object is created with new | Once, when the class is initialized |
| Lifetime | Until the object is garbage collected | Until the class is unloaded (usually program end) |
| Accessed through | Object reference: obj.name | Class name: ClassName.count |
| Use inside a static method | Only through an object | Directly |
| Use inside an instance method | Directly | Directly |
| Default value | Yes (0, false, null) | Yes (0, false, null) |
| Other name | Object variable, non-static field | Class variable |
| Typical use | Name, balance, roll number | Counter, constant, shared setting |
Static constants: static final
static finalmeans one shared copy that can never change. Name it inUPPER_SNAKE_CASE.- It must be assigned exactly once: at the declaration or inside a static block.
- Compile-time constants (a primitive or String with a constant value) are copied (inlined) by javac into every class that uses them.
- JDK examples:
Math.PI,Integer.MAX_VALUE, andSystem.out(astatic final PrintStream).
public class AppConfig {
public static final String APP_NAME = "LearnCodeGuru";
public static final int MAX_LOGIN_ATTEMPTS = 3;
public static final double GST_RATE = 0.18;
private AppConfig() { } // only constants, no objects needed
public static void main(String[] args) {
double price = 1000;
System.out.println(APP_NAME + " allows " + MAX_LOGIN_ATTEMPTS + " attempts");
System.out.println("Price with GST: " + (price + price * GST_RATE)); // 1180.0
// GST_RATE = 0.12; // compile error: cannot assign a value to final variable
}
} Static method
- Declared with
static. It belongs to the class and is called asClassName.method()without creating an object. - It works only with its parameters and static data, unless you pass in or create an object.
- It cannot use
thisorsuper, because there is no current object. - Best for utility work whose result depends only on the inputs:
Math.sqrt,Integer.parseInt,Arrays.sort,String.valueOf. mainis static so the JVM can call it before any object exists.- Real life: a calculator button for square root works the same for everyone. You do not need "your own calculator object" to press it.
public class MathUtil {
private MathUtil() { } // utility class: no objects
static int square(int n) {
return n * n;
}
static boolean isEven(int n) {
return n % 2 == 0;
}
static long factorial(int n) {
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
static int max(int a, int b, int c) {
return Math.max(a, Math.max(b, c));
}
public static void main(String[] args) {
System.out.println(MathUtil.square(7)); // 49
System.out.println(MathUtil.isEven(10)); // true
System.out.println(MathUtil.factorial(5)); // 120
System.out.println(max(4, 19, 8)); // 19 (same class: simple name works)
}
} Rules of static methods
- Remember the one-line rule: static can use static directly; static needs an object to use instance members.
| Inside a static method, can you... | Answer | Reason or workaround |
|---|---|---|
| Read or change a static variable? | Yes | Both belong to the class |
| Call another static method? | Yes | By simple name or ClassName.method() |
| Read an instance variable directly? | No | Error: non-static variable cannot be referenced from a static context. Use obj.field. |
| Call an instance method directly? | No | Create or receive an object, then call obj.method() |
Use this or super? | No | There is no current object |
| Be overridden in a subclass? | No | A same-signature static method in the child hides it |
Be declared abstract? | No | Abstract needs overriding, and static methods cannot be overridden |
| Be overloaded? | Yes | Different parameter lists are fine |
Be synchronized? | Yes | It locks the Class object, for example Counter.class |
| Be called with an object reference? | Yes, but avoid | The compiler uses the reference type; it misleads readers |
public class Student {
static String college = "LCG College";
String name = "Asha";
static void printCollege() {
System.out.println(college); // OK: static uses static
// System.out.println(name); // ERROR: non-static variable name
// System.out.println(this.name); // ERROR: cannot use this in a static context
Student s = new Student();
System.out.println(s.name); // OK: through an object
}
void printAll() {
System.out.println(name + " - " + college); // instance method sees both
printCollege(); // and can call static methods
}
public static void main(String[] args) {
Student.printCollege();
new Student().printAll();
}
} Differences between instance method and static method
| Point | Instance method | Static method |
|---|---|---|
| Keyword | No keyword | static |
| Belongs to | The object | The class |
| Call syntax | obj.method() | ClassName.method() |
| Needs an object? | Yes | No |
| Access instance variables | Directly | Only through an object reference |
| Access static variables | Directly | Directly |
this and super | Allowed | Not allowed |
| Overriding | Yes (runtime polymorphism) | No (only method hiding) |
| Binding | Dynamic, at runtime | Static, at compile time |
| Typical use | Behaviour that depends on object state: deposit, withdraw | Utilities, factories, counters: Math.max, List.of |
Static block
static { ... }is a block that runs once, automatically, when the class is initialized.- It runs before
main(for the main class) and before any constructor of that class. - Use it to initialize static variables that need logic: filling a lookup map, reading configuration, loading a native library.
- A class may have many static blocks. They run top to bottom, together with static field initializers, in source order.
- It cannot use
this, and it cannot throw a checked exception out. An uncaught exception inside causesExceptionInInitializerError.
import java.util.HashMap;
import java.util.Map;
public class StateCodes {
static final Map<String, String> CODES = new HashMap<>();
static {
System.out.println("static block 1: loading codes");
CODES.put("AP", "Andhra Pradesh");
CODES.put("TS", "Telangana");
CODES.put("KA", "Karnataka");
}
static {
System.out.println("static block 2: total = " + CODES.size());
}
public static void main(String[] args) {
System.out.println("main started");
System.out.println(CODES.get("TS"));
}
}
// Output:
// static block 1: loading codes
// static block 2: total = 3
// main started
// Telangana Static class (static nested class)
- Java has no static top-level class.
staticis allowed only on a class declared inside another class. That is called a static nested class. - A static nested class does not need an object of the outer class. Create it with
new Outer.Nested(). - It can use the static members of the outer class directly, even private ones. To use instance members it needs an outer object.
- It can have its own fields, constructors, methods, and static members, like any normal class.
- Use it to group a helper type that belongs with the outer class:
Map.Entry, a linked listNode, aBuilder. - The compiler creates a separate file for it:
Outer$Nested.class. - Real life: a university has departments. A department record can be described without picking one particular vice-chancellor object, so it fits a static nested class.
public class University {
private static String universityName = "LCG University";
private String vcName = "Dr. Rao";
static class Department {
private final String deptName;
Department(String deptName) {
this.deptName = deptName;
}
void show() {
System.out.println(deptName + " - " + universityName); // outer static: OK
// System.out.println(vcName); // ERROR: needs a University object
}
void showVc(University u) {
System.out.println("VC: " + u.vcName); // OK through an object
}
}
public static void main(String[] args) {
University.Department cse = new University.Department("CSE");
Department ece = new Department("ECE"); // inside University the short name works
cse.show();
ece.show();
cse.showVc(new University());
}
} Differences between static nested class and inner class
| Point | Static nested class | Inner (non-static) class |
|---|---|---|
| Declaration | static class Nested { } inside the outer class | class Inner { } inside the outer class |
| Needs an outer object? | No | Yes |
| Creating an object | new Outer.Nested() | outer.new Inner() |
| Access outer static members | Yes, directly | Yes, directly |
| Access outer instance members | Only through an outer object reference | Yes, directly |
| Hidden reference to the outer object | No | Yes (Outer.this) |
| Memory | Lighter, no leak risk | Keeps the outer object alive; can leak memory |
| Static members inside it | Allowed | Allowed since Java 16 (earlier only static final constants) |
| JDK examples | Map.Entry, builders, list nodes | Iterators over the outer collection data |
| Prefer it when | The nested type does not need outer object state | The nested type works on one specific outer object |
public class Outer {
private static int shared = 10;
private int value = 20;
static class StaticNested {
void show() {
System.out.println("shared = " + shared);
}
}
class Inner {
void show() {
System.out.println("shared = " + shared + ", value = " + value);
}
}
public static void main(String[] args) {
Outer.StaticNested a = new Outer.StaticNested(); // no Outer object needed
a.show();
Outer outer = new Outer();
Outer.Inner b = outer.new Inner(); // needs an Outer object
b.show();
}
} Ways to access static members
| Way | Example | Recommended? |
|---|---|---|
| Class name | Math.max(3, 7), Visitor.getTotalVisitors() | Yes, the clearest way |
| Simple name inside the same class | totalVisitors++ inside Visitor | Yes |
| Static import | import static java.lang.Math.sqrt; then sqrt(16) | Yes, for a few well-known names |
| Object reference | v1.getTotalVisitors() | No, it compiles with a warning and looks like instance data |
| null reference | Visitor v = null; v.getTotalVisitors(); | It works (no NullPointerException) but is confusing. Never do this. |
import static java.lang.Math.PI;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
public class Circle {
public static void main(String[] args) {
double r = 5;
System.out.println("Area = " + PI * pow(r, 2)); // no Math. prefix
System.out.println("sqrt(81) = " + sqrt(81));
}
} When to use static and when not to
| Use static for | Avoid static for |
|---|---|
Constants: static final double GST_RATE | Data that belongs to one object: name, balance, marks |
Pure utility methods: MathUtil.square | Behaviour that differs per object or per subclass |
Factory methods: Color.ofRgb, List.of | Mutable global state shared across threads and tests |
| Object counters and ID generators | Avoiding the work of passing an object as a parameter |
Helper nested types: Node, Builder, Entry | Code you need to mock, replace, or override in tests |
The program entry point: main | Large static collections that keep growing (memory leaks) |
Advanced — Static Members
How static members live in memory
- When the JVM loads a class it creates one
Classobject and one set of static fields for that class. Since Java 8 static fields are stored in the heap with the class mirror, and class metadata such as method bytecode lives in Metaspace. - Each
newcreates an object on the heap that holds only instance fields. Static fields are never copied into objects. - So 1000
Studentobjects mean 1000 copies ofnamebut only one copy ofcollege. That is a memory saving. - Strictly, a static field is one copy per class per class loader. Application servers that load the same class twice get two copies.
| Item | Where it lives | How many copies |
|---|---|---|
| Instance field | Inside each object on the heap | One per object |
| Static field | With the class (heap, Class mirror) | One per class (per class loader) |
| Local variable / parameter | Thread stack frame | One per method call |
| Method bytecode (static or instance) | Metaspace (class metadata) | One per class |
Class loading and initialization order
- A class is initialized on its first active use:
new, calling a static method, reading or writing a non-constant static field,Class.forName, or being the main class. - It is not initialized by: declaring a variable of that type, reading a compile-time
static finalconstant, or creating an array likenew Demo[5]. - Order: parent static init, then child static init (once only). Then for every
new: parent instance blocks and constructor, then child instance blocks and constructor.
class Parent {
static { System.out.println("1. Parent static block"); }
{ System.out.println("3. Parent instance block"); }
Parent() { System.out.println("4. Parent constructor"); }
}
class Child extends Parent {
static { System.out.println("2. Child static block"); }
{ System.out.println("5. Child instance block"); }
Child() { System.out.println("6. Child constructor"); }
}
public class InitOrder {
public static void main(String[] args) {
new Child();
System.out.println("--- second object ---");
new Child(); // static blocks do NOT run again: only 3, 4, 5, 6
}
} Method hiding: static methods are not overridden
- If a child class declares a static method with the same signature as a parent static method, it hides the parent method.
- Which version runs is decided at compile time by the reference type, not by the object type.
- Putting
@Overrideon a static method is a compile error. A static method cannot hide an instance method, and an instance method cannot override a static one (both are compile errors).
class Animal {
static void info() { System.out.println("Animal static info"); }
void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
static void info() { System.out.println("Dog static info"); } // hides
@Override
void sound() { System.out.println("Dog barks"); } // overrides
}
public class HidingDemo {
public static void main(String[] args) {
Animal a = new Dog();
a.info(); // Animal static info (reference type decides)
a.sound(); // Dog barks (object type decides)
Dog.info(); // Dog static info
}
} Static nested class in practice: the Builder pattern
- A builder collects optional settings step by step and then creates an immutable object.
- It is a static nested class because building a pizza must not require an existing pizza object.
- The outer constructor is private, so
Pizza.Builderis the only way to create aPizza.
public class Pizza {
private final String size;
private final boolean cheese;
private final boolean olives;
private Pizza(Builder b) {
this.size = b.size;
this.cheese = b.cheese;
this.olives = b.olives;
}
@Override
public String toString() {
return size + " pizza, cheese=" + cheese + ", olives=" + olives;
}
public static class Builder {
private final String size;
private boolean cheese;
private boolean olives;
public Builder(String size) { this.size = size; }
public Builder cheese() { cheese = true; return this; }
public Builder olives() { olives = true; return this; }
public Pizza build() { return new Pizza(this); }
}
public static void main(String[] args) {
Pizza p = new Pizza.Builder("Large").cheese().olives().build();
System.out.println(p); // Large pizza, cheese=true, olives=true
}
} Static factory methods
- A static factory is a static method that returns an object instead of making callers use
newdirectly. - Benefits: meaningful names (
ofGray), caching and reuse (Integer.valueOf,Boolean.valueOf), and the freedom to return a subtype (List.of). - Often combined with a private constructor so all creation goes through the factories.
public class Color {
private static final Color RED = new Color(255, 0, 0);
private final int r, g, b;
private Color(int r, int g, int b) {
this.r = r;
this.g = g;
this.b = b;
}
static Color red() { return RED; } // cached: same object every time
static Color ofRgb(int r, int g, int b) { return new Color(r, g, b); }
static Color ofGray(int level) { return new Color(level, level, level); }
@Override
public String toString() { return "rgb(" + r + "," + g + "," + b + ")"; }
public static void main(String[] args) {
System.out.println(Color.red()); // rgb(255,0,0)
System.out.println(Color.ofGray(128)); // rgb(128,128,128)
System.out.println(Color.red() == Color.red()); // true
}
} Lazy singleton with a static holder class
- A private static nested class is not initialized until it is first used.
- The JVM initializes classes under a lock, so this gives a thread-safe, lazy singleton without
synchronizedcode.
public class Logger {
private Logger() {
System.out.println("Logger created");
}
private static class Holder {
static final Logger INSTANCE = new Logger();
}
public static Logger getInstance() {
return Holder.INSTANCE; // Holder is initialized on the first call only
}
void log(String msg) {
System.out.println("[LOG] " + msg);
}
public static void main(String[] args) {
System.out.println("app started"); // printed before "Logger created"
Logger.getInstance().log("first");
Logger.getInstance().log("second");
System.out.println(Logger.getInstance() == Logger.getInstance()); // true
}
} Static variables and thread safety
- A static variable is shared by every thread.
count++is read, add, write, so two threads can lose updates. - Fixes:
AtomicInteger, asynchronized staticmethod (locksClassName.class), or avoid shared mutable static state. - Static initialization itself is thread-safe, but later changes to static fields are not.
import java.util.concurrent.atomic.AtomicInteger;
public class TicketCounter {
private static int unsafeCount = 0;
private static final AtomicInteger safeCount = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 10_000; i++) {
unsafeCount++; // race condition
safeCount.incrementAndGet(); // atomic
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("unsafe = " + unsafeCount); // often less than 20000
System.out.println("safe = " + safeCount.get()); // always 20000
}
} static in interfaces, enums, and records
- Interface fields are implicitly
public static final. Since Java 8 interfaces can have static methods, called only asInterfaceName.method()and not inherited by implementing classes. - Enum constants are
public static finalobjects, andvalues()andvalueOf()are static methods. - Records can have static fields and static methods, but no extra instance fields.
- Nested interfaces, enums, and records are implicitly static.
interface Validator {
int MIN_LENGTH = 8; // implicitly public static final
static boolean isStrong(String password) {
return password.length() >= MIN_LENGTH
&& password.chars().anyMatch(Character::isDigit);
}
}
record Point(int x, int y) {
static final Point ORIGIN = new Point(0, 0);
static Point of(int x, int y) {
return new Point(x, y);
}
}
public class StaticEverywhere {
public static void main(String[] args) {
System.out.println(Validator.isStrong("learn2code")); // true
System.out.println(Point.ORIGIN); // Point[x=0, y=0]
System.out.println(Point.of(3, 4)); // Point[x=3, y=4]
}
} Common static pitfalls
| Pitfall | What goes wrong | Fix |
|---|---|---|
Mutable public static field | Any code can change it; hidden coupling | Make it private with methods, or final |
| Static collection that only grows | Memory leak: it lives until the class unloads | Clear it, bound it, or use a cache with eviction |
| Calling a static method through an object | Readers think it is per-object behaviour | Always call through the class name |
| Static state in unit tests | Tests pass alone but fail when run together | Reset in @BeforeEach or remove the static |
| Static method that needs different behaviour | It cannot be overridden or easily mocked | Use an instance method behind an interface |
Using an instance field inside main | Compile error: non-static from a static context | Create an object first, then use obj.field |
| Exception in a static block | ExceptionInInitializerError, then NoClassDefFoundError on later use | Handle errors inside the block and fail with a clear message |
Tricky Interview Points
Q1) What is the static keyword in Java?
Answer It marks a member that belongs to the class instead of to each object. static can be applied to variables, methods, blocks, nested classes, and imports.
Q2) What is a static variable? Give a real-life example.
Answer A class variable with one shared copy for all objects, created when the class is initialized. Example: the college name for all students, or the interest rate for all savings accounts.
Q3) What is the difference between a static variable and an instance variable?
Answer A static variable has one copy per class and is accessed by class name. An instance variable has one copy per object and is accessed through an object reference.
Q4) Can a static method access instance variables?
Answer Not directly, because it has no current object. It can use them only through an object reference that is passed in or created inside the method.
Q5) Why can we not use this or super inside a static method?
Answer this and super refer to the current object. A static method runs without any object, so there is nothing for them to refer to.
Q6) Can we override a static method?
Answer No. A child static method with the same signature hides the parent method. The call is resolved at compile time using the reference type, so there is no runtime polymorphism.
Q7) Can static methods be overloaded?
Answer Yes. Overloading only needs a different parameter list, and it is resolved at compile time, so static methods can be overloaded freely.
Q8) Why is main static? What happens if we remove static?
Answer The launcher must call main before any object exists, so it calls it by class name. Without static, older Java versions compile the class but the launcher fails with an error saying main is not static. Java 25 added instance main methods (JEP 512) as a feature for small programs, but public static void main remains the standard form.
Q9) When does a static block run? Can a class have more than one?
Answer Once, when the class is initialized on first active use. A class can have many static blocks; they run in source order together with static field initializers.
Q10) Can we run a program without main by using a static block?
Answer Only in Java 6 and earlier. Since Java 7 the launcher checks for main before initializing the class, so it reports that the main method is missing.
Q11) Can a top-level class be static?
Answer No. static is allowed only on nested classes. A top-level class marked static is a compile error.
Q12) What is a static nested class, and how is it different from an inner class?
Answer A static nested class does not need an outer object and has no hidden outer reference. An inner class needs an outer object, can use its instance fields directly, and keeps it alive through Outer.this.
Q13) How do you create an object of a static nested class?
Answer With new Outer.Nested(). Inside the outer class you can write new Nested(). For an inner class you need outer.new Inner().
Q14) Can a static nested class access private members of the outer class?
Answer Yes. It can access outer static members directly, even private ones. It can access private instance members only through a reference to an outer object.
Q15) Can a local variable or a constructor be static?
Answer No. Local variables live in a method call stack frame, and constructors always build an object. Both are compile errors with static.
Q16) Can an abstract method be static?
Answer No. An abstract method must be overridden, and static methods cannot be overridden, so abstract static is a compile error.
Q17) Are static variables thread-safe?
Answer No. They are shared by all threads. Changes like count++ need AtomicInteger, synchronization, or a design without shared mutable static state.
Q18) What happens if you call a static method using a null reference?
Answer It runs normally without a NullPointerException, because the compiler uses only the reference type. It is legal but very confusing.
Q19) What is a static import?
Answer import static lets you use static members without the class name, for example import static java.lang.Math.PI. Use it for a few well-known names only.
Q20) Where are static variables stored in memory?
Answer Since Java 8 they are stored in the heap together with the Class object of their class. Class metadata such as method bytecode is in Metaspace.
Q21) What is ExceptionInInitializerError?
Answer It is thrown when a static initializer or static field initializer throws an exception. Later attempts to use that class fail with NoClassDefFoundError.
Simple Programs
Employee ID generator with a shared company name
public class Employee {
static final String COMPANY = "LearnCodeGuru Pvt Ltd";
private static int nextId = 1001;
private final int id;
private final String name;
Employee(String name) {
this.id = nextId++;
this.name = name;
}
static int employeesCreated() {
return nextId - 1001;
}
void print() {
System.out.println(id + " " + name + " @ " + COMPANY);
}
public static void main(String[] args) {
new Employee("Asha").print(); // 1001 Asha @ LearnCodeGuru Pvt Ltd
new Employee("Ravi").print(); // 1002 Ravi @ ...
new Employee("Kiran").print(); // 1003 Kiran @ ...
System.out.println("Total: " + Employee.employeesCreated()); // 3
}
} Class topper using static variables
public class Result {
private static String topperName = "none";
private static int topperMarks = -1;
private final String name;
private final int marks;
Result(String name, int marks) {
this.name = name;
this.marks = marks;
if (marks > topperMarks) {
topperMarks = marks;
topperName = name;
}
}
static void printTopper() {
System.out.println("Topper: " + topperName + " (" + topperMarks + ")");
}
public static void main(String[] args) {
new Result("Asha", 87);
new Result("Ravi", 93);
new Result("Kiran", 78);
Result.printTopper(); // Topper: Ravi (93)
}
} Temperature converter utility class
public final class TempConverter {
private TempConverter() { } // no objects
static double toFahrenheit(double celsius) {
return celsius * 9 / 5 + 32;
}
static double toCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
static double toKelvin(double celsius) {
return celsius + 273.15;
}
public static void main(String[] args) {
System.out.println(TempConverter.toFahrenheit(100)); // 212.0
System.out.println(TempConverter.toCelsius(212)); // 100.0
System.out.println(TempConverter.toKelvin(0)); // 273.15
}
} Overloaded static methods: Calculator
public class Calculator {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
static int add(int... nums) {
int sum = 0;
for (int n : nums) {
sum += n;
}
return sum;
}
public static void main(String[] args) {
System.out.println(Calculator.add(2, 3)); // 5 (int, int)
System.out.println(Calculator.add(2.5, 3.5)); // 6.0 (double, double)
System.out.println(Calculator.add(1, 2, 3, 4)); // 10 (varargs)
}
} Static nested class: linked list Node
public class MyLinkedList {
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
private Node head;
private static int listsCreated = 0;
MyLinkedList() {
listsCreated++;
}
void addFirst(int value) {
Node n = new Node(value);
n.next = head;
head = n;
}
void print() {
for (Node cur = head; cur != null; cur = cur.next) {
System.out.print(cur.data + " ");
}
System.out.println();
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.addFirst(30);
list.addFirst(20);
list.addFirst(10);
list.print(); // 10 20 30
System.out.println("lists = " + listsCreated); // 1
}
} Static nested class returning two values: MinMax
public class Stats {
static class MinMax {
final int min;
final int max;
MinMax(int min, int max) {
this.min = min;
this.max = max;
}
}
static MinMax findMinMax(int[] values) {
int min = values[0];
int max = values[0];
for (int v : values) {
if (v < min) min = v;
if (v > max) max = v;
}
return new MinMax(min, max);
}
public static void main(String[] args) {
Stats.MinMax r = Stats.findMinMax(new int[] {42, 7, 19, 88, 3});
System.out.println("min = " + r.min + ", max = " + r.max); // min = 3, max = 88
}
} Predict the output: static vs instance counter
public class CounterDemo {
static int staticCount = 0;
int instanceCount = 0;
CounterDemo() {
staticCount++;
instanceCount++;
}
public static void main(String[] args) {
CounterDemo a = new CounterDemo();
CounterDemo b = new CounterDemo();
CounterDemo c = new CounterDemo();
System.out.println(a.instanceCount + " " + b.instanceCount + " " + c.instanceCount); // 1 1 1
System.out.println(CounterDemo.staticCount); // 3
}
} Problem Solving Tricks
- One-line rule: static can use static directly; static needs an object to use instance members.
- Ask "is this value the same for every object?" If yes, it can be static. If no, it must be an instance variable.
- Always call static members through the class name, never through an object reference.
public static finalconstants useUPPER_SNAKE_CASE:MAX_SIZE,GST_RATE.- Utility classes:
finalclass,privateconstructor, only static methods (likeMathandCollections). - Make a nested class static by default. Remove static only when it truly needs the outer object.
- Static methods hide, instance methods override.
@Overrideon a static method will not compile. - Keep mutable static fields
private, and useAtomicIntegeror synchronization when threads share them. - A static block runs once per class, not once per object. Instance blocks run on every
new. - Unit tests must not depend on leftover static state. Reset it in
@BeforeEachor avoid the static.
Practice Programs List
- Count how many objects of a
Carclass were created using a static variable. - Create a
Studentclass where the college name is static and roll numbers are generated automatically from a static counter. - Write a
SavingsAccountclass with a static interest rate. Change the rate once and print the interest for three accounts. - Write a utility class
StringUtilwith static methodsreverse,isPalindrome, andcountVowels. - Write
static int gcd(int a, int b)andstatic int lcm(int a, int b)and call them without creating an object. - Add two static blocks and a constructor to a class, create two objects, and confirm the blocks run once.
- Inside a static method, try to use an instance field and
this. Write down the exact compiler errors. - Show method hiding:
ParentandChildboth havestatic void hello(). Call it through a Parent reference holding a Child object. - Create a static nested class
AddressinsideCustomerand create it frommainwithnew Customer.Address(...). - Rewrite the same nested class as an inner class and compare how objects are created.
- Build a
PizzaorLaptopclass with a static nestedBuilder. - Implement a lazy singleton
Configwith a private static holder class and prove only one object is created. - Run two threads that increment a static
int10,000 times each. Then fix it withAtomicInteger. - Use static imports for
Math.PI,Math.pow, andMath.sqrtin a circle and hypotenuse program.