×

Advanced Coding & Software Engineering Program

Duration: 1 Year (12 Months)

Join our premium 1-year program to master cutting-edge technologies and become an industry-ready Software Engineer!

Course Coverage

  • Languages: C, C++, Java, JavaScript, Python
  • Web Technologies: HTML, CSS, Bootstrap 5, MERN Stack, Full Stack Development
  • Databases: MySQL, MongoDB
  • Data Science Libraries: Pandas, NumPy
  • Development Tools: Visual Studio Code, IntelliJ IDEA, PyCharm, Postman, Git, GitHub
  • Cloud Platforms: Vercel, MongoDB Atlas

Program Highlights

  • Live Classes: Interactive sessions with real-time doubt resolution
  • Hands-On Sessions: Practical coding exercises to build real-world skills
  • Industry Experts: Learn from professionals with years of experience
  • Live Project: Work on real-world projects to apply your skills
  • Get Certificate: Earn a professional certificate upon program completion

Course Fee: Only ₹1020 / month
Limited Period Offer!

Java static Keyword Tutorial for Beginners



Last Updated on: 5th Nov 2025 23:26:19 PM

Welcome to this complete and beginner-friendly tutorial on the static keyword in Java! The static keyword is used to create class-level members that belong to the class itself, not to any specific object.

This means:
One copy is shared by all objects.

 

This tutorial covers:

  • All 4 types of static members

  • Real-world analogies

  • Programs with and without static

  • Restrictions on static methods (explained in detail)

  • Why main() is static

  • Runnable examples

 

What is static?

The static keyword in Java is used to define members (variables, methods, blocks, classes) that belong to the class, not to instances (objects).

 

The static keyword in Java is used for memory management.
It means that the member (variable, method, or block) belongs to the class, not to any specific object.

 

So you can access it without creating an object of the class.

 

Think of static as a shared blackboard in a classroom.
All students (objects) can read/write on it — there’s only one blackboard (one copy).

 
static int count = 0;  // One copy for all objects

 

The static Can Be:

 Type

 Name

 Belongs To

 Example

 1

 Variable

 Class

static int count;

 2

 Method

 Class

static void print()

 3

 Block

 Class

static { ... }

 4

 Nested Class

 Class

static class Inner

 

Where Can We Use static?

Use Case Description
static variable Shared by all objects of the class
static method Can be called without creating an object
static block Runs once when the class is loaded
static class (nested) Used for grouping helper classes

 

1. static Variable (Class Variable)

A static variable is shared by all objects of the class. There is only one copy in memory, no matter how many objects you create.It gets memory only once at the time of class loading.

 

Example (With static):

class StudentWithStatic {
    int rollNo;
    String name;
    static String college = "IKeySkills"; // static variable

    StudentWithStatic(int r, String n) {
        rollNo = r;
        name = n;
    }

    void display() {
        System.out.println(rollNo + " " + name + " - " + college);
    }
}

public class WithStaticExample {
    public static void main(String[] args) {
        StudentWithStatic s1 = new StudentWithStatic(1, "Amit");
        StudentWithStatic s2 = new StudentWithStatic(2, "Neha");

        s1.display();
        s2.display();

        // changing college name using one object
        s1.college = "TechWorld";

        System.out.println("\nAfter changing college name using s1:");
        s1.display();
        s2.display();  // also changed
    }
}

 

Output:

1 Amit - IKeySkills
2 Neha - IKeySkills

After changing college name using s1:
1 Amit - TechWorld
2 Neha - TechWorld

 

Explanation:

  • college is declared as static, so both s1 and s2 share the same memory.

  • Changing it from one object affects all others.

  • college is static only one copy in memory

  • All objects see the same value

  • Change once → updated everywhere

 

Perfect for: Company name, PI value, counters, config

 

Example (Without static):

Every object of the class gets its own copy of instance variables.
So, if we change the variable for one object, it doesn’t affect others.

class StudentWithoutStatic {
    int rollNo;
    String name;
    String college = "IKeySkills"; // non-static variable

    StudentWithoutStatic(int r, String n) {
        rollNo = r;
        name = n;
    }

    void display() {
        System.out.println(rollNo + " " + name + " - " + college);
    }
}

public class WithoutStaticExample {
    public static void main(String[] args) {
        StudentWithoutStatic s1 = new StudentWithoutStatic(1, "Amit");
        StudentWithoutStatic s2 = new StudentWithoutStatic(2, "Neha");

        s1.display();
        s2.display();

        // changing college name for one student
        s1.college = "TechWorld";

        System.out.println("\nAfter changing s1's college:");
        s1.display();
        s2.display();  // remains same
    }
}

 

Output:

1 Amit - IKeySkills
2 Neha - IKeySkills

After changing s1's college:
1 Amit - TechWorld
2 Neha - IKeySkills

 

Explanation:

  • Each object (s1, s2) has its own copy of college.

  • Changing s1.college didn’t affect s2.college.

 

Example 2 

Program Without static Variable (Each object has its own copy) 

class Employee {
    int id;
    String name;
    int loginCount = 0;  // Each employee has own counter

    Employee(int i, String n) {
        id = i;
        name = n;
        loginCount++;  // Only this object counts
        System.out.println(name + " logged in " + loginCount + " time(s)");
    }

    public static void main(String[] args) {
        Employee e1 = new Employee(101, "Amit");
        Employee e2 = new Employee(102, "Priya");
        Employee e3 = new Employee(103, "Rahul");
    }
}

 

Output:

Amit logged in 1 time(s)
Priya logged in 1 time(s)
Rahul logged in 1 time(s)

 

Problem:
Each employee thinks they logged in only once — no shared count!

 

Program With static Variable (Shared counter)

class Employee {
    int id;
    String name;
    static int totalLogins = 0;  // Shared by all employees

    Employee(int i, String n) {
        id = i;
        name = n;
        totalLogins++;  // Shared count increases
        System.out.println(name + " logged in. Total system logins: " + totalLogins);
    }

    public static void main(String[] args) {
        Employee e1 = new Employee(101, "Amit");
        Employee e2 = new Employee(102, "Priya");
        Employee e3 = new Employee(103, "Rahul");
    }
}

 

Output:

Amit logged in. Total system logins: 1
Priya logged in. Total system logins: 2
Rahul logged in. Total system logins: 3

 

Success!
totalLogins is shared — all objects see the same increasing count.

 

2. static Method (Class Method)

A static method belongs to the class and can be called without creating an object. You can call it directly using the class name — no need to create an object.

 

Example 1

class MathUtils {
    static int multiply(int a, int b) {
        return a * b;
    }

    public static void main(String[] args) {
        int result = MathUtils.multiply(4, 5);
        System.out.println("Result: " + result);
    }
}

Output:

Result: 20

 

Like Math.pow(2, 3) — no object needed!

 

Example 2

class MathHelper {
    static int square(int n) {
        return n * n;
    }

    static void showMessage() {
        System.out.println("This is a static method example!");
    }
}

public class StaticMethodExample {
    public static void main(String[] args) {
        System.out.println("Square of 5 is: " + MathHelper.square(5));
        MathHelper.showMessage();
    }
}

 

Why use static here?

  • These are utility functions (like inbuilt Math.sqrt()).

  • They don’t depend on any object data.

 

Rules:

  • Can access only static variables directly.

  • Can call other static methods directly.

  • To access non-static variables, you must create an object.

 

Restrictions for static Methods in Java

Static methods have important limitations because they don’t belong to any object. A static method belongs to the class, not to any object.So, it can only directly access static members of the class.

 

Here are the 3 key restrictions with full explanation:

 

1. Cannot access non-static (instance) variables directly

Static methods do not have access to instance variables,because instance variables belong to objects — and no object is created when a static method runs.

 

Example: Invalid Code

class Test {
    int x = 10;  // Instance variable

    void show() {
        System.out.println("Hello");
    }

    static void display() {
        System.out.println(x);  // ERROR!
        show();                 // ERROR!
        System.out.println(this.x);  // ERROR!
    }
}

 

Why errors occur:

  1. x is an instance variable — it exists only when you create an object using new Test().
    → But inside display(), there’s no object, so Java doesn’t know which object’s x to use.

  2. show() is an instance method — it also needs an object to be called.
    → You can’t call show() directly from a static method.

  3. this.x — the keyword this refers to the current object.
    → But since static methods are not tied to any object, this cannot be used here.

 

Correct Way

static void display() {
    Test obj = new Test();  // Create object first
    System.out.println(obj.x);
    obj.show();
}

 

Explanation:

  • When you write Test obj = new Test();, you create an instance of the class.

  • Now that an object exists:

    • obj.x → accesses that object’s x value.

    • obj.show() → calls that object’s instance method.

 

Key Takeaway:

  • Static = Class level (no object needed).

  • Instance = Object level (needs object).

  • To access instance members inside a static method, you must create an object first.

 

2. Cannot call non-static methods directly

Static methods can only call other static methods directly.If you want to call a non-static method, you must first create an object.

 

Example:

class Example {
    void greet() {
        System.out.println("Hello, from non-static method!");
    }

    static void display() {
        // greet(); ? Error: Cannot call non-static method directly
        Example obj = new Example();  // ? create object
        obj.greet();
    }

    public static void main(String[] args) {
        display();
    }
}

 

Output:

Hello, from non-static method!

 

Why?

  • Non-static methods belong to objects.

  • Static methods belong to the class — so you need an object reference.

 

3. Cannot use this or super keywords

The keywords this and super refer to the current object and the parent class object, respectively.Static methods are called without creating any object, so these keywords don’t make sense inside them.

 

Example:

class Demo {
    int a = 10;

    static void show() {
        // System.out.println(this.a); ? ERROR
        System.out.println("Static method cannot use 'this' or 'super'");
    }
}

 

Why?
this means “this object,” but no object exists when a static method is called.

 

4. Static methods cannot be overridden (in true sense)

You can define a static method with the same name in a subclass,but it’s method hiding, not overriding.

 

Example:

class Parent {
    static void display() {
        System.out.println("Parent static method");
    }
}

class Child extends Parent {
    static void display() {
        System.out.println("Child static method");
    }
}

public class StaticOverrideExample {
    public static void main(String[] args) {
        Parent obj = new Child();
        obj.display(); // Output: Parent static method
    }
}

 

Explanation:

  • The call is resolved at compile-time, not runtime.

  • Hence, static methods are hidden, not overridden.

 

5. Static methods cannot access instance-specific data

They don’t know which object they’re supposed to operate on.

 

For example, in a bank system, a static method can’t display one user’s balance
unless you pass an object as a parameter.

Example:

class BankAccount {
    int balance = 1000;

    static void showBalance() {
        // System.out.println(balance); ? ERROR
    }

    static void showBalance(BankAccount acc) { // ? Correct way
        System.out.println("Balance: " + acc.balance);
    }

    public static void main(String[] args) {
        BankAccount a1 = new BankAccount();
        BankAccount.showBalance(a1); // ? works fine
    }
}

 

3. static Block

A static block is used to initialize static variables and runs only once, when the class is loaded into memory.

Example:

class Config {
    static String courseName;

    static {
        courseName = "Java Full Stack";
        System.out.println("Static block executed!");
    }
}

public class StaticBlockExample {
    public static void main(String[] args) {
        System.out.println("Main method started.");
        System.out.println("Course: " + Config.courseName);
    }
}

 

Output:

Static block executed!
Main method started.
Course: Java Full Stack

 

Why use static block?

  • For one-time setup like database connection, configuration loading, etc.

 

4. static Nested Class 

You can declare a static nested class inside another class.It doesn’t need an object of the outer class to be created.

 

Example:

class Outer {
    static int outerValue = 10;

    static class Inner {
        void show() {
            System.out.println("Outer value: " + outerValue);
        }
    }
}

public class StaticNestedExample {
    public static void main(String[] args) {
        Outer.Inner obj = new Outer.Inner(); // no need for Outer object
        obj.show();
    }
}

 

Why use static nested classes?

  • To group helper or related classes logically inside one class.

  • Often used in Builder pattern or Utility classes.

 

Real-Life Example: Bank Interest Rate 

class Bank {
    static double rateOfInterest = 7.5; // same for all banks
    String accountHolder;
    double balance;

    Bank(String name, double bal) {
        accountHolder = name;
        balance = bal;
    }

    void showDetails() {
        System.out.println(accountHolder + " | Balance: rs" + balance + " | Interest: " + rateOfInterest + "%");
    }

    static void changeRate(double newRate) {
        rateOfInterest = newRate; // static method to change value
    }
}

public class StaticRealLifeExample {
    public static void main(String[] args) {
        Bank b1 = new Bank("Ravi", 10000);
        Bank b2 = new Bank("Sneha", 20000);

        b1.showDetails();
        b2.showDetails();

        Bank.changeRate(8.0); // changing interest rate globally

        b1.showDetails();
        b2.showDetails();
    }
}

 

Output:

Ravi | Balance: rs 10000.0 | Interest: 7.5%
Sneha | Balance: rs 20000.0 | Interest: 7.5%
Ravi | Balance: rs 10000.0 | Interest: 8.0%
Sneha | Balance: rs 20000.0 | Interest: 8.0%

 

Perfect use of static: One rate → affects all accounts

 

Final Quiz

class Test {
    static int x = 5;

    static {
        x = 10;
        System.out.println("A");
    }

    public static void main(String[] args) {
        System.out.println("B: " + x);
    }
}

 

Output:

A
B: 10

 

You’ve Mastered static!

Happy Coding! You've got this!yes


Online - Chat Now
Let’s Connect

Inquiry Sent!

Your message has been successfully sent. We'll get back to you soon!

iKeySkills Logo