Java Notes
Complete guide to the static keyword in Java — static variables, methods, blocks, inner classes, imports, and understanding class-level vs instance-level members.
The static keyword marks a member as belonging to the class rather than to any specific object. A static member exists once, is shared by all instances, and can be accessed without creating an object.
Think of it this way: instance members are like personal items each student carries. Static members are like the classroom whiteboard — shared by everyone, only one copy exists.
static Variables (Class Variables)
A static variable is shared across ALL objects of the class:
1. Alice - Springfield High 2. Bob - Springfield High 3. Charlie - Springfield High Total students: 3
Memory Layout
| Student.totalStudents = 3 | s1: name="Alice" | |
|---|---|---|
| Student.schoolName = "..." | rollNumber=1 |
static vs Instance Variables
| Feature | Static Variable | Instance Variable |
|---|---|---|
| Belongs to | Class | Object |
| Memory | Method Area (one copy) | Heap (one per object) |
| Access | ClassName.var or obj.var | obj.var only |
| Lifetime | Program start to end | Object creation to GC |
| Default value | Yes (0, null, false) | Yes (0, null, false) |
| Use case | Counters, constants, shared config | Object-specific data |
static Methods (Class Methods)
Static methods belong to the class and can be called without an object:
Max: 20 Average: 87.6 7 is prime? true 5! = 120
Restrictions in Static Methods
Static methods cannot access instance members directly:
public class Demo {
private int instanceVar = 10;
private static int staticVar = 20;
public static void staticMethod() {
System.out.println(staticVar); // ✅ Static can access static
// System.out.println(instanceVar); // ❌ Cannot access instance variable
// instanceMethod(); // ❌ Cannot call instance method
// System.out.println(this); // ❌ No 'this' in static context
}
public void instanceMethod() {
System.out.println(instanceVar); // ✅ Instance can access instance
System.out.println(staticVar); // ✅ Instance can access static
staticMethod(); // ✅ Instance can call static
}
}Why? Static methods can be called without an object. Without an object, there's no instance state to access.
static Block (Static Initializer)
A static block runs once when the class is first loaded into memory:
public class DatabaseConfig {
private static String url;
private static String username;
private static String password;
private static Map<String, String> settings;
// Static block - runs once when class loads
static {
System.out.println("Loading database configuration...");
settings = new HashMap<>();
try {
// Simulate loading from config file
url = "jdbc:mysql://localhost:3306/myapp";
username = "admin";
password = "secret123";
settings.put("pool_size", "10");
settings.put("timeout", "30000");
System.out.println("Configuration loaded successfully");
} catch (Exception e) {
System.err.println("Failed to load config: " + e.getMessage());
throw new RuntimeException("Cannot start without config", e);
}
}
// Multiple static blocks execute in order
static {
System.out.println("Additional initialization...");
settings.put("retry_count", "3");
}
public static String getUrl() { return url; }
public static String getSetting(String key) { return settings.get(key); }
}
public class Main {
public static void main(String[] args) {
System.out.println("Accessing DatabaseConfig...");
System.out.println("URL: " + DatabaseConfig.getUrl());
System.out.println("Pool: " + DatabaseConfig.getSetting("pool_size"));
}
}Loading database configuration... Configuration loaded successfully Additional initialization... Accessing DatabaseConfig... URL: jdbc:mysql://localhost:3306/myapp Pool: 10
Execution Order
public class ExecutionOrder {
// Static variable with initializer
private static int x = initX();
// Static block
static {
System.out.println("2. Static block");
}
// Instance initializer
{
System.out.println("4. Instance initializer");
}
// Constructor
public ExecutionOrder() {
System.out.println("5. Constructor");
}
private static int initX() {
System.out.println("1. Static variable initializer");
return 10;
}
public static void main(String[] args) {
System.out.println("3. Main method");
new ExecutionOrder();
new ExecutionOrder();
}
}1. Static variable initializer 2. Static block 3. Main method 4. Instance initializer 5. Constructor 4. Instance initializer 5. Constructor
Note: Static initialization happens ONCE. Instance initialization happens for EACH object.
static Constants
The most common use of static is with final to create constants:
public class Constants {
public static final double PI = 3.14159265358979;
public static final int MAX_USERS = 1000;
public static final String APP_NAME = "MyApplication";
public static final String VERSION = "2.1.0";
// Private constructor - cannot instantiate utility class
private Constants() {
throw new AssertionError("Cannot instantiate Constants");
}
}
// Usage
public class Main {
public static void main(String[] args) {
double circumference = 2 * Constants.PI * 5;
System.out.println("App: " + Constants.APP_NAME + " v" + Constants.VERSION);
System.out.println("Circumference: " + circumference);
}
}App: MyApplication v2.1.0 Circumference: 31.4159265358979
static Inner Class
A static inner class doesn't have access to the outer class's instance members:
10 -> 20 -> 30 -> null
Factory Method Pattern with static
[INFO] Application: Application started [INFO] Database: Connected to database [ERROR] Database: Query timeout Same instance? true
static Import
Import static members directly to avoid qualifying with class name:
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
import static java.lang.System.out;
public class StaticImportDemo {
public static void main(String[] args) {
// Without static import: Math.sqrt(), System.out.println()
// With static import:
double hypotenuse = sqrt(pow(3, 2) + pow(4, 2));
out.println("Hypotenuse: " + hypotenuse);
out.println("Circle area (r=5): " + PI * pow(5, 2));
}
}Hypotenuse: 5.0 Circle area (r=5): 78.53981633974483
Use sparingly — overusing static import makes code less readable.
Real-World Example: Counter/ID Generator
ORD-000001 | Alice | $150.0 ORD-000002 | Bob | $89.99 ORD-000003 | Charlie | $245.5
Common Mistakes
- Accessing instance members from static methods:
``java private String name; public static void printName() { System.out.println(name); // ❌ Cannot access instance var from static } ``
- Using
thisin static context:
``java public static void method() { this.doSomething(); // ❌ No 'this' in static } ``
- Overriding static methods (you can't!):
``java class Parent { public static void greet() { System.out.println("Parent"); } } class Child extends Parent { public static void greet() { System.out.println("Child"); } // This is METHOD HIDING, not overriding! No polymorphism. } Parent p = new Child(); p.greet(); // Prints "Parent" — resolved at compile time! ``
- Mutable static state in multi-threaded code:
``java private static int counter; // ❌ Race condition in multi-threaded code // Fix: use AtomicInteger or synchronization ``
- Overusing static — making everything static:
``java // ❌ Procedural code disguised as OOP public class UserService { public static void createUser(String name) { } public static User getUser(int id) { } public static void deleteUser(int id) { } } // ✅ Use instance methods — allows polymorphism, testing, etc. ``
Best Practices
- Use
staticfor utility methods that don't depend on state (Math.abs()) - Use
static finalfor constants - Use static factory methods instead of constructors for controlled creation
- Avoid mutable static variables — they're global state
- Make utility classes non-instantiable (private constructor)
- Be careful with static in multi-threaded environments
- Don't use static just to avoid creating objects — that defeats OOP
Interview Questions
Q1: Can we override static methods? No. Static methods are resolved at compile time (early binding). A child class can define the same method (method hiding), but it's not polymorphic.
Q2: Why is main() method static? JVM needs to call main() without creating an object of the class. If main() were non-static, JVM would need to instantiate the class first — creating a chicken-and-egg problem.
Q3: Can a static method access instance variables? Not directly. It needs an object reference: new MyClass().instanceVar. Static methods have no this.
Q4: What is the difference between static and instance initialization blocks? Static blocks run once when the class loads. Instance blocks run every time an object is created, before the constructor.
Q5: Can a class be declared static? Only inner classes can be static. Top-level classes cannot be declared static.
Q6: What is method hiding? When a subclass defines a static method with the same signature as the parent. Unlike overriding, the method called depends on the reference type, not the object type.
Q7: When should you use static methods? When the method doesn't use any instance state — utility methods, factory methods, and operations that logically belong to the class rather than any particular instance.
Q8: What is the difference between static method and instance method? Static methods belong to the class, can be called without an object, cannot access this or instance variables, and are resolved at compile time. Instance methods belong to objects, need an object to call, can access both static and instance members, and support polymorphism (dynamic dispatch).
Q9: Can a static block throw an exception? Yes, but only unchecked exceptions. If a checked exception occurs, it must be caught within the block. If a static block throws an exception, the class fails to load and ExceptionInInitializerError is thrown. The class cannot be used after this.
Q10: What is the difference between static import and regular import? Regular import imports classes: import java.util.Math; then use Math.sqrt(). Static import imports static members directly: import static java.lang.Math.sqrt; then use sqrt() without the class name. Overusing static imports reduces code readability.
Q11: Can we serialize static variables? No. Serialization saves object state (instance variables). Static variables belong to the class, not the object, so they're not serialized. After deserialization, static variables will have whatever value is current in the JVM, not the value at serialization time.
Q12: Why should utility classes have a private constructor? Utility classes (like Math, Arrays) contain only static methods and shouldn't be instantiated. A private constructor prevents new MathUtils() which would be meaningless. Also add throw new AssertionError() inside to prevent reflection-based instantiation.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for static Keyword in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, oops, static, keyword
Related Java Master Course Topics