Tuesday, 15 September 2015

Java Tutorial : Java Static Variable (Access Using ClassName)

Master Core Java Concepts!

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

Subscribe Now on YouTube

Accessing Static Variables Using Class Name in Java

In Java, a static variable (also known as a class variable) is declared using the static keyword. This indicates to the compiler that only one copy of the variable exists across all instances of the class.

While static variables can technically be accessed via an object reference, the standard best practice is to access them directly using the Class Name (ClassName.variableName). This reinforces that the variable belongs to the class itself, not to any individual instance.

Code Example: Defining Class with Static and Instance Variables

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

  // Static variable (shared among all student objects)
  static int schoolCode;

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

Modifying Static Variables via Class Name

In the demo below, we create three separate student objects, set unique instance variables for each, and update the static variable schoolCode directly using Student.schoolCode = 5000;:

public class StudentDemo {
  public static void main(String[] args) {
    // Creating three distinct 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;

    // Setting the static variable directly using the class name
    Student.schoolCode = 5000;

    // Printing details for each student
    john.printInstanceAndStaticVariables();
    dave.printInstanceAndStaticVariables();
    julie.printInstanceAndStaticVariables();
  }
}

Key Takeaways

✔️ Direct Access: Use ClassName.variableName to assign or access static variables without needing an object instance.

✔️ Shared Memory: Changing schoolCode affects every object because they all reference the exact same memory location.

✔️ Cleaner Code: Accessing static members via the class name improves code readability and prevents confusion with instance fields.


Watch More Java Tutorials:

No comments:

Post a Comment

Tutorials