Java Keywords – this, final, static
This page explains three extremely important Java keywords with simple examples: this, final, and static. These keywords help developers write clean, optimized, and predictable object-oriented programs.
1. The this Keyword
The this keyword is used to refer to the current object. It solves variable shadowing problems, calls current object methods, and even invokes constructors.
✔ this to refer instance variables
class Car {
int speed;
Car(int speed) {
this.speed = speed; // refers to instance variable
}
}
✔ this() to call another constructor
class Bike {
int mileage;
Bike() {
this(40); // calling parameterized constructor
}
Bike(int m) {
mileage = m;
}
}
2. The final Keyword
final is used to prevent modification. It can be applied to variables, methods, and classes.
✔ final variable (constant)
final int MAX_SPEED = 120;
✔ final method (cannot be overridden)
class Vehicle {
final void show() { System.out.println("Vehicle"); }
}
✔ final class (cannot be inherited)
final class Engine {}
3. The static Keyword
static is used to create members that belong to the class rather than objects. It is memory efficient and ideal for shared data.
✔ static variable (shared)
class Student {
static String college = "NBKRIST";
String name;
}
✔ static method (can run without object)
class MathUtil {
static int square(int x) {
return x * x;
}
}
✔ static block (runs before main)
class Demo {
static {
System.out.println("Static block executed");
}
}
Practice Questions – Click to Reveal Answers
1️⃣ What is the use of this keyword?
It refers to the current object and resolves variable shadowing.
2️⃣ What does final prevent?
It prevents modification: final variables cannot change, final methods cannot be overridden, and final classes cannot be inherited.
3️⃣ Why use static keyword?
Static members belong to the class and are shared across objects, improving memory efficiency.
Quick Summary
- this → refers to current object, calls constructors, resolves shadowing.
- final → prevents modification (constants, no override, no inheritance).
- static → class-level sharing, utility methods, static blocks.