Local Variable Rules in Java
- Local variables are declared in a blocks, methods or constructors
- Access modifiers cannot be used for declaring local variables.
- Stack memory is used for storing local variables and function calls and has a fixed size
- Local variables do not have default values. You must initialize them before using.
- Local variables declared in loops or blocks are destroyed after the block or loop completes
Rules for Local Variables in Java:
Declaration and Initialization:
- A local variable must be declared before it can be used.
- Local variables must be initialized explicitly before use, as Java does not provide default values for them.
Scope:
- The scope of a local variable is limited to the block (method, constructor, or loop) in which it is declared.
- The variable is destroyed when the block exits.
Access Modifiers:
- Local variables cannot have access modifiers (e.g.,
public,private,protected). - They can only have
finalas a modifier to make them immutable.
- Local variables cannot have access modifiers (e.g.,
No Default Value:
- Unlike instance variables, local variables do not have default values. You must initialize them before using.
Shadowing:
- A local variable can shadow (hide) a class or instance variable with the same name. Use
thisto refer to the instance variable explicitly.
- A local variable can shadow (hide) a class or instance variable with the same name. Use
Loops and Blocks:
- Local variables declared in loops or blocks are destroyed after the block or loop completes.
Lambda Expressions:
- Local variables referenced in lambda expressions must be effectively final, meaning they cannot be reassigned after their initial assignment.
Comments
Post a Comment