What is the static Keyword in Java?
The static keyword indicates that a member belongs to the class itself rather than to instances of the class.
1. Static Variables (Class Variables)
Shared across all objects of the class. Only one copy exists in memory.
class Counter {
static int count = 0; // Static variable - shared
Counter() {
count++;
System.out.println("Object created. Total objects: " + count);
}
public static void main(String[] args) {
Counter c1 = new Counter(); // count = 1
Counter c2 = new Counter(); // count = 2
Counter c3 = new Counter(); // count = 3
}
}
2. Static Methods
Can be called without creating an object. They can only access static members directly.
class MathUtils {
public static int square(int x) {
return x * x;
}
public static int add(int a, int b) {
return a + b;
}
}
public class Test {
public static void main(String[] args) {
// Calling static methods without object
System.out.println(MathUtils.square(5)); // 25
System.out.println(MathUtils.add(10, 20)); // 30
}
}
3. Static Block
Executed once when the class is first loaded into memory (before main).
class Database {
static String connectionUrl;
static String username;
// Static block for initialization
static {
System.out.println("Static block executed");
connectionUrl = "jdbc:mysql://localhost:3306/mydb";
username = "admin";
}
static void connect() {
System.out.println("Connecting to: " + connectionUrl);
}
public static void main(String[] args) {
System.out.println("Main method started");
Database.connect();
}
}
// Output:
// Static block executed
// Main method started
// Connecting to: jdbc:mysql://localhost:3306/mydb
Rules for static
- Static methods cannot access non-static members directly
- Cannot use this or super in static context
- Static nested classes can have static members
Employee ID Generator Example
class Employee {
private static int nextId = 1000;
private int empId;
private String name;
Employee(String name) {
this.name = name;
this.empId = nextId++;
}
void display() {
System.out.println("ID: " + empId + ", Name: " + name);
}
static void showNextId() {
System.out.println("Next ID will be: " + nextId);
}
public static void main(String[] args) {
Employee e1 = new Employee("Alice");
Employee e2 = new Employee("Bob");
e1.display(); // ID: 1000, Name: Alice
e2.display(); // ID: 1001, Name: Bob
Employee.showNextId(); // Next ID will be: 1002
}
}
Learn Java programming fundamentals at Online Learner!
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
