Working with Variables and Scoping
1. Declaring Variables
| Form | Syntax | Example |
|---|---|---|
| Declaration | type name; | int count; |
| Init | type name = value; | String s = "hi"; |
| Multiple | type a, b, c; | int x = 1, y = 2; |
| Type inference | var name = expr; | var list = new ArrayList<String>(); |
2. Understanding Variable Scope
| Scope | Lifetime | Visibility |
|---|---|---|
| Class (static) | Class loaded → unloaded | Per class |
| Instance | Object lifetime | Per instance |
| Method (local) | Method invocation | Method body |
| Block | Block execution | Inside { } |
| Loop variable | Loop only | Loop body |
3. Understanding Type Inference
| Context | Allowed | Notes |
|---|---|---|
| Local variable | Yes | var x = 10; |
| For-each loop | Yes | for (var s : list) |
| Lambda parameter | Yes (Java 11+) | (var a, var b) -> a+b |
| Field | No | Not permitted |
| Method parameter/return | No | Not permitted |
| Without initializer | No | var 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");
| Convention | Rule |
|---|---|
| Modifiers | public static final |
| Naming | UPPER_SNAKE_CASE |
| Initialization | At declaration or in static block |
5. Understanding Variable Shadowing
| Scenario | Behavior |
|---|---|
| Local hides field | Use this.field |
| Subclass hides static field | Use Super.field |
| Inner class hides outer | Use OuterClass.this.field |
6. Using Static Variables
Example: Static counter
class Counter {
private static int totalInstances = 0;
Counter() { totalInstances++; }
static int getCount() { return totalInstances; }
}
| Property | Behavior |
|---|---|
| Storage | Class metadata (one per class) |
| Access | ClassName.field |
| Init order | Static blocks/fields run when class loads |
7. Using Instance Variables
| Property | Detail |
|---|---|
| Storage | Object instance (heap) |
| Defaults | Auto-initialized (0/false/null) |
| Access | this.field or obj.field |
8. Understanding Variable Initialization
| Variable Type | Default Init | Required Before Use |
|---|---|---|
| Local | None | Yes (compile error) |
| Instance field | Zero/null | No |
| Static field | Zero/null | No |
final field | None | Must be assigned exactly once |
9. Working with System Properties
| Method | Purpose |
|---|---|
System.getProperty(key) | Read property |
System.setProperty(key, val) | Set at runtime |
System.getProperties() | All properties |
| Common keys | user.home, user.dir, java.version, os.name, line.separator, file.encoding |
| CLI flag | java -Dapp.env=prod App |
10. Working with Environment Variables
| Method | Purpose |
|---|---|
System.getenv(name) | Read single var |
System.getenv() | Map of all env vars |
Note: Environment variables are read-only from Java; cannot be modified.