Sobes.tech
Junior

What types of variables exist in Java?

sobes.tech AI

Answer from AI

In Java, there are three main types of variables:

  1. Local variables:

    • Declared inside methods, constructors, or blocks.
    • Accessible only within the block where they are declared.
    • Do not have default values; they must be initialized before use.
    • Their lifetime is limited to the execution of the method or block.
  2. Instance variables / Fields:

    • Declared inside a class but outside methods, constructors, and blocks.
    • Belong to a specific object (instance of the class).
    • Created when the object is created and destroyed with it.
    • Have default values (0 for numeric types, null for objects, false for booleans).
    • Accessed through the object.
  3. Static variables / Class variables:

    • Declared inside a class with the static keyword, outside methods, constructors, and blocks.
    • Belong to the class itself, not to any specific object.
    • Created when the class is loaded and exist until the class is unloaded.
    • Only one copy of the static variable exists for the entire class, regardless of how many objects are created.
    • Have default values (like instance variables).
    • Can be accessed through the class or through an object (preferably through the class for clarity).
public class VariableTypes {

    // Static class variable
    static int staticVariable = 10;

    // Instance variable
    String instanceVariable;

    public VariableTypes(String name) {
        // Initialize the instance variable in the constructor
        this.instanceVariable = name;
    }

    public void methodExample() {
        // Local variable
        int localVar = 20;
        System.out.println("Local variable: " + localVar);
        System.out.println("Instance variable: " + this.instanceVariable);
        System.out.println("Static variable: " + VariableTypes.staticVariable);
    }

    public static void main(String[] args) {
        // Access static variable through the class
        System.out.println("Static variable from main: " + VariableTypes.staticVariable);

        VariableTypes obj1 = new VariableTypes("Object 1");
        VariableTypes obj2 = new VariableTypes("Object 2");

        // Each object has its own copy of the instance variable
        System.out.println("Instance variable obj1: " + obj1.instanceVariable);
        System.out.println("Instance variable obj2: " + obj2.instanceVariable);

        // They share the same static variable
        obj1.methodExample();
        obj2.methodExample();

        // Changing the static variable through one object will reflect on all
        VariableTypes.staticVariable = 30;
        System.out.println("Static variable after change through class: " + VariableTypes.staticVariable);
        System.out.println("Static variable from obj1 after change: " + obj1.staticVariable); // Access through object is possible but not recommended
    }
}