Variables and Constants in Java
Understand how to declare variables with explicit types, use type inference with var, and define constants with the final keyword.
Declaring Variables
A variable is a named container that stores a value in memory. In Java every variable must have a declared type. You can declare a variable and assign its value later, or declare and initialize it on the same line.
1. Declare and Initialize
The most common form: declare the type, give it a name, and assign a value in one line.
2. Declare First, Assign Later
You can declare a variable without a value and assign it later. The variable must be assigned before it is used.
3. Reassigning Variables
A variable can be reassigned to a new value of the same type at any point.
Type Inference with var
`var` was introduced in Java 10 as part of JEP 286. Instead of writing the type explicitly, you let the compiler infer it from the assigned value. The type is still static and fixed at compile time — `var` is not dynamic like JavaScript's `let`.
1. var — Basic Usage
Use `var` when the type is obvious from the right-hand side. It reduces boilerplate without losing type safety.
2. var — Limitations
`var` can only be used for local variables with an initializer. It cannot be used for fields, method parameters, or return types.
Constants with final
A constant is a variable whose value cannot be reassigned after it is set. In Java, constants are declared with the `final` keyword. By convention, constant names are written in `UPPER_SNAKE_CASE`.
1. Local Constants (final in a method)
A `final` local variable can be assigned once and never changed after that.
2. Class-Level Constants (static final)
For constants shared across the whole class, declare them as `static final` fields.
3. Combining var and final
You can use both `var` and `final` together for a type-inferred local constant.
Naming Rules & Variable Scope
Java has strict naming rules for variables and a well-defined scoping model. A variable is only accessible within the block `{}` where it is declared.
1. Variable Naming Rules & Conventions
Java variable names must follow certain rules and should follow camelCase by convention.
2. Variable Scope
A variable only exists inside the `{}` block where it is declared. It cannot be accessed outside that block.