Tuesday, 15 September 2015

Java Tutorial : Java Static Variable

Master Core Java Concepts!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!

Subscribe Now on YouTube

What Are Static Variables in Java?

In Java, a static variable (also known as a class variable or static field) is any variable declared with the static modifier inside a class.

Declaring a variable as static instructs the compiler that exactly one copy of this variable exists in memory, regardless of how many times the class is instantiated. While instance variables maintain individual values for every created object, a static variable is shared among all objects of that class.

Instance vs. Static Variables

  • Instance Variables (e.g., name, age): Each object gets its own distinct copy. Changing the name or age of one student has no effect on any other student.
  • Static Variable (e.g., schoolCode): A single shared copy exists for all instances. All students share the exact same school code.

Code Example: Defining Class with Static and Instance Variables

class Student {
  // Instance variables (unique to each object)
  String name;
  int age;

  // Static variable (shared across all objects)
  static String schoolCode = "SCH101";

  public void printStudentDetails() {
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
    System.out.println("School Code: " + schoolCode);
  }
}

Demonstration: Shared Memory in Action

public class StudentDemo {
  public static void main(String[] args) {
    // Creating three separate student objects
    Student john = new Student();
    john.name = "John";
    john.age = 6;

    Student dave = new Student();
    dave.name = "Dave";
    dave.age = 7;

    Student julie = new Student();
    julie.name = "Julie";
    julie.age = 5;

    // Displaying details
    john.printStudentDetails();
    dave.printStudentDetails();
    julie.printStudentDetails();
  }
}

Key Takeaways

✔️ Single Copy in Memory: Only one copy of a static variable is created and loaded when the class is loaded.

✔️ Common to All Instances: Any update to a static variable reflects across every object of that class.

✔️ Best Practice Access: Access static members directly using ClassName.variableName rather than through object references.


Watch More Java Tutorials:

No comments:

Post a Comment

Tutorials