Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Variables and scope in Java

Variables and scope in Java: A Java variable has a declared or inferred type, scope, and lifetime; variables include fields, parameters, local variables, and array components.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

variables

A Java variable has a declared or inferred type, scope, and lifetime; variables include fields, parameters, local variables, and array components.

Keep local scopes narrow, use final for references that should not be reassigned, and choose names that reveal a value’s unit and meaning.

Fields receive default values, but a local variable must be definitely assigned before reading; final does not make the referenced object immutable.

Shadowing can hide a field behind a parameter, var requires an initializer and is not dynamic typing, and a lambda captures only final or effectively final locals.

Default fields print defaults=0,false, the lambda captures effectively final values for captured=10, and shadow shows 9 versus field=0.

Examples

import java.util.function.IntSupplier;
public class Main {
  static int defaultCount; boolean defaultFlag;
  public static void main(String[] args) {
    int local=7; final int base=3; IntSupplier captured=()->base+local;
    var instance=new Main();
    System.out.println("defaults="+defaultCount+","+instance.defaultFlag);
    System.out.println("captured="+captured.getAsInt());
    int defaultCount=9; System.out.println("shadow="+defaultCount+",field="+Main.defaultCount);
  }
}

Result

defaults=0,false
captured=10
shadow=9,field=0

Default fields print defaults=0,false, the lambda captures effectively final values for captured=10, and shadow shows 9 versus field=0.

Sources