Working with Variables and Scoping

1. Declaring Variables

FormSyntaxExample
Declarationtype name;int count;
Inittype name = value;String s = "hi";
Multipletype a, b, c;int x = 1, y = 2;
Type inferencevar name = expr;var list = new ArrayList<String>();

2. Understanding Variable Scope

ScopeLifetimeVisibility
Class (static)Class loaded → unloadedPer class
InstanceObject lifetimePer instance
Method (local)Method invocationMethod body
BlockBlock executionInside { }
Loop variableLoop onlyLoop body

3. Understanding Type Inference

ContextAllowedNotes
Local variableYesvar x = 10;
For-each loopYesfor (var s : list)
Lambda parameterYes (Java 11+)(var a, var b) -> a+b
FieldNoNot permitted
Method parameter/returnNoNot permitted
Without initializerNovar x; illegal

4. Working with Constants

Example: Constants

public static final int MAX_USERS = 1000;
public static final String API_URL = "https://api.example.com";
private static final List<String> ROLES = List.of("ADMIN", "USER");
ConventionRule
Modifierspublic static final
NamingUPPER_SNAKE_CASE
InitializationAt declaration or in static block

5. Understanding Variable Shadowing

ScenarioBehavior
Local hides fieldUse this.field
Subclass hides static fieldUse Super.field
Inner class hides outerUse OuterClass.this.field

6. Using Static Variables

Example: Static counter

class Counter {
    private static int totalInstances = 0;
    Counter() { totalInstances++; }
    static int getCount() { return totalInstances; }
}
PropertyBehavior
StorageClass metadata (one per class)
AccessClassName.field
Init orderStatic blocks/fields run when class loads

7. Using Instance Variables

PropertyDetail
StorageObject instance (heap)
DefaultsAuto-initialized (0/false/null)
Accessthis.field or obj.field

8. Understanding Variable Initialization

Variable TypeDefault InitRequired Before Use
LocalNoneYes (compile error)
Instance fieldZero/nullNo
Static fieldZero/nullNo
final fieldNoneMust be assigned exactly once

9. Working with System Properties

MethodPurpose
System.getProperty(key)Read property
System.setProperty(key, val)Set at runtime
System.getProperties()All properties
Common keysuser.home, user.dir, java.version, os.name, line.separator, file.encoding
CLI flagjava -Dapp.env=prod App

10. Working with Environment Variables

MethodPurpose
System.getenv(name)Read single var
System.getenv()Map of all env vars
Note: Environment variables are read-only from Java; cannot be modified.