Junior — Middle
What is the difference between class properties and local variables inside methods?
sobes.tech AI
Answer from AI
Class properties (fields) and local variables inside methods differ in several key aspects:
-
Scope:
- Class properties are accessible in all methods of the class (depending on access modifiers).
- Local variables are only visible within the block or method where they are declared.
-
Lifetime:
- Properties exist as long as the object (or class, if the field is static) exists.
- Local variables are created when the method is called and destroyed when it exits.
-
Initialization:
- Class properties are assigned default values (e.g.,
0for numbers,nullfor objects) if not explicitly initialized. - Local variables must be explicitly initialized before use; otherwise, the compiler will generate an error.
- Class properties are assigned default values (e.g.,
Example:
public class Example {
private int field; // class property
public void method() {
int localVar = 10; // local variable
System.out.println(field); // accessible
System.out.println(localVar); // accessible
}
}