Static Variables In Class

Static Variables In Class

A school program needs reliable data and clear rules. A static field belongs to the class rather than one instance. A shared school name can be read without constructing a Student.

  1. Understand

    A static field belongs to the class rather than one instance.

  2. Apply

    Trace the Java example, predict its output and explain the result before running it.

  3. Avoid mistakes

    Changing a static field affects the shared value; instance fields can still differ between students.

Static Variables In Class

In Java, a static variable is a class-level variable — meaning it belongs to the class, not to instances (objects) of the class. All instances of a class share the same static variable. This makes static variables useful when you want to store common data across all objects of a class.

Static vs Instance Variables

Before diving deep, let's distinguish:

  • Instance variables are unique to each object.
  • Static variables are shared by all instances of a class.

Syntax of Static Variables

class MyClass {
  static int count = 0; // Static variable
}

Example: Sharing a Static Variable Across Objects

Let’s look at a program that demonstrates how a static variable behaves across multiple objects:

class Student {
    static int studentCount = 0; // Shared across all instances
    String name;

    Student(String name) {
        this.name = name;
        studentCount++; // Increments shared counter
    }

    void showStudent() {
        System.out.println("Name: " + name);
        System.out.println("Total Students: " + studentCount);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Alice");
        Student s2 = new Student("Bob");

        s1.showStudent();
        s2.showStudent();
    }
}
Name: Alice
Total Students: 2
Name: Bob
Total Students: 2

Explanation

Java · example discussed here

class Student {
    static int studentCount = 0; // Shared across all instances
    String name;

    Student(String name) {
        this.name = name;
        studentCount++; // Increments shared counter
    }

    void showStudent() {
        System.out.println("Name: " + name);
        System.out.println("Total Students: " + studentCount);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Alice");
        Student s2 = new Student("Bob");

        s1.showStudent();
        s2.showStudent();
    }
}

Even though we create two students, studentCount is not duplicated. It remains a single variable shared across all Student objects. When both constructors increment the counter, they’re modifying the same memory location.

Accessing Static Variables

You can access static variables using:

  1. Class name (preferred)
  2. Instance name (allowed, but not recommended)
System.out.println(Student.studentCount); // Recommended
System.out.println(s1.studentCount);      // Valid but not ideal

Why Use Static Variables?

They come in handy when you need:

  • A counter across all objects (e.g., number of users, students, sessions)
  • Common configuration or constant values

Another Example: Static Variable for Configuration

class AppConfig {
    static String ENV = "PRODUCTION";
}

public class ConfigTest {
    public static void main(String[] args) {
        System.out.println("Environment: " + AppConfig.ENV);
    }
}
Environment: PRODUCTION

What Happens If You Modify Static Variable?

If one object or the class itself modifies a static variable, the change reflects across all references.

class Counter {
    static int value = 5;
}

public class Test {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();

        c1.value++;
        System.out.println(c2.value); // Outputs 6
    }
}
6

Do Static Variables Work in Inheritance?

Yes — static variables are inherited, but they belong to the class they are defined in. They are not polymorphic. Here's an example:

class Parent {
    static int staticVar = 100;
}

class Child extends Parent {}

public class InheritTest {
    public static void main(String[] args) {
        System.out.println(Child.staticVar); // Accessing staticVar from Parent
    }
}
100

Common Pitfalls

  • Confusing static variables with instance variables can lead to shared-state bugs.
  • Modifying static variables from multiple threads needs synchronization.
  • Referencing static variables via object names can confuse code readability.

Summary

  • Static variables are class-level — they are shared across all instances.
  • Use static when you need shared configuration, counters, or constants.
  • Prefer accessing them via the class name for clarity.

Real-Life Analogy

Imagine a school: each student has a name (instance variable), but they all belong to the same school (static variable). Changing the school name affects all students, no matter how many you create.

Practice Task

Try this:

  • Create a Car class that tracks the total number of cars created using a static variable.
  • Display the car’s model and the total count in a method.

Doing is learning — go for it!

Important boundaries and mistakes

Changing a static field affects the shared value; instance fields can still differ between students.

Try the school example

Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Changing a static field affects the shared value; instance fields can still differ between students..

Java 17 · Main.java · complete practice program

public class Main  {
  interface Named  {
    String label();
  }
  static class Student implements Named  {
    static String school = "River School";
    String name;
    Student(String name)  {
      this.name = name;
    }
    public String label()  {
      return name;
    }
  }
  public static void main(String[] args)  {
    System.out.println(Student.school);
  }
}

Worked answer and reasoning

Java 17 · Main.java · source repeated for this answer

public class Main  {
  interface Named  {
    String label();
  }
  static class Student implements Named  {
    static String school = "River School";
    String name;
    Student(String name)  {
      this.name = name;
    }
    public String label()  {
      return name;
    }
  }
  public static void main(String[] args)  {
    System.out.println(Student.school);
  }
}

Expected output

River School

A static field belongs to the class rather than one instance. A shared school name can be read without constructing a Student.

Changing a static field affects the shared value; instance fields can still differ between students.

Run with javac Main.java, then java Main. The declaration inside Main keeps the helper type available to this standalone example.

Check your understanding

For the complete practice program in this lesson, which output is expected on Java 17?
Choose one answer. You can try again.

Answer and explanation

River School

A static field belongs to the class rather than one instance. A shared school name can be read without constructing a Student. Changing a static field affects the shared value; instance fields can still differ between students.

What to remember

A static field belongs to the class rather than one instance. A shared school name can be read without constructing a Student. Changing a static field affects the shared value; instance fields can still differ between students.

Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide and Java 17 language specification.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Static Methods In Class →