this & static keyword
this refers to the current object — it clears up confusion when a parameter and a field share the same name.
A static member belongs to the class, not to any one object — all objects share it, like a common counter.
class Counter {
static int total = 0;
Counter() { total++; }
}- this = your own current object
- static = shared at the class level
- Accessible via ClassName.member without an object
A this() call runs one constructor from another (of the same class) — avoiding repeated initialization code. Full detail is in the Constructor topic, but remember: this() must always be the constructor's first line.
A static variable is class-level, not object-level — it exists exactly once in memory for the whole class (whether you make 1 object or 1000). Classic use-case: a counter that tracks how many objects have been made so far — every time an object is created (in the constructor), this counter gets incremented, and all objects see the same shared value.
Static variables are created the moment the class loads (inside the JVM), and can be accessed even without creating an object — via ClassName.variableName.
class User {
static int totalUsers = 0;
User() { totalUsers++; }
}
new User(); new User(); new User();
System.out.println(User.totalUsers); // 3Static methods are called directly via ClassName.methodName(), without creating an object — Math.max(), Math.sqrt(), Integer.parseInt() are classic examples. The entire "Math" class is full of static methods, because maths operations don't need any specific object state.
Only static members can be accessed *directly* inside a static method (because "this" has no meaning without an object — the JVM has no idea which object). If you need an instance member, you'll have to explicitly create/pass an object.
A static { } block runs once, the moment the class loads — even before any object is created, right at the start of the program (when the JVM first uses that class). It's used to initialize complex static variables that can't be set with a simple assignment (like reading config from a file, or needing multiple lines of logic).
A class can have multiple static blocks too — they run in declaration order, top to bottom.
class Config {
static String env;
static {
env = loadFromFile(); // complex setup, ek baar hi hota hai
System.out.println("Config loaded!");
}
}