Local Variables
Local variables are defined within a method and are only accessible within that method; they cannot be accessed outside the method. They are created when the method is invoked and destroyed after the method execution completes. Therefore, local variables are method-scoped variables that are not stored on the heap but on the stack.
Example:
javapublic void calculateSum() { int a = 5; // Local variable int b = 10; // Local variable int sum = a + b; System.out.println("Sum = " + sum); }
In this example, the variables a, b, and sum are all local variables and can only be accessed within the calculateSum method.
Static Variables
Static variables, also known as class variables, are defined at the class level and belong to the class itself rather than to any instance of the class. This means that static variables are shared among all instances of the class. They are initialized when the class is loaded and destroyed when the program terminates.
Example:
javapublic class Counter { public static int count = 0; // Static variable public static void increment() { count++; } }
In this example, count is a static variable, and it is shared among all instances of the Counter class, regardless of how many instances are created.
Instance Variables
Instance variables are defined within a class but outside of methods, constructors, or any blocks. Each time an instance of the class is created, a new copy of the instance variables is created, and each instance has its own copy.
Example:
javapublic class Student { public String name; // Instance variable public Student(String name) { this.name = name; } }
In this example, name is an instance variable. Each time a new Student object is created, the object has its own copy of the name variable.
Summary
- Local variables: Defined within a method, with a lifetime limited to the duration of the method call.
- Static variables: Defined at the class level, shared among all instances of the class, with a lifetime spanning the entire program runtime.
- Instance variables: Defined within the class but outside methods and constructors, with each instance having its own copy, and a lifetime matching the object instance.