Junior — Middle
What is the difference between class fields and local variables inside methods in Java?
sobes.tech AI
Answer from AI
Class fields (instance variables or static fields) and local variables inside methods in Java differ in scope, lifetime, and storage location:
-
Class fields:
- Declared inside the class but outside methods.
- Stored in the object (if non-static) or in the class area (if static).
- Maintain their value between method calls.
- Accessible from different methods of the class (depending on access level).
-
Local variables:
- Declared inside a method.
- Exist only during the execution of the method.
- Stored on the call stack.
- Not accessible outside the method in which they are declared.
Example:
public class Example {
int field = 10; // class field
public void method() {
int localVar = 5; // local variable
System.out.println(field + localVar);
}
}
Here, field maintains the state of the object, while localVar exists only during the execution of the method.