Final and local type inference
What you will learn
A final local variable can be assigned only once. Local type inference with var lets the compiler infer a local variable’s static type from its initializer. Neither feature turns Java into a dynamically typed language.
public class Main { public static void main(String[] args) { final int capacity = 40; int booked = 12; System.out.println(capacity - booked); }}Expected output:
28Capacity stays fixed while the number booked is a separate variable.
How it works
Use final int seats = 20; when the binding should not be reassigned. Use var count = 3; when the initializer makes the type clear; the inferred type is int. Local var declarations require an initializer of an inferable type, and var is not a general field or method return type. It was introduced in Java 10.
public class Main { public static void main(String[] args) { var count = 3; count = 5; System.out.println(count); }}Expected output:
5The inferred int variable permits later int assignments.
Common mistakes
A final reference prevents reassignment of the reference; it does not make the referenced object immutable. var count = 3; count = "five"; is also invalid because count remains an int.
Try it yourself
Use final for a fixed box capacity and var for a changing count, then print the remaining space.
These are local Java practice tasks, not automatically graded ByteMind exercises. Use a patched JDK; no network or third-party dependency is needed.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Final and local type inference — knowledge check
Check your understanding of final and local type inference.
What type does var count = 3 infer?
What does final prevent for a local variable?