Java - Variables & Constants
Variables & Constants
Primitives vs References
Java has 8 primitive types stored by value, and reference types (objects/arrays) stored as references.
// primitives
byte b=1; short s=2; int i=3; long l=4L; float f=1.0f; double d=2.0; char c='A'; boolean ok=true;
// reference
String name = "Ada"; // reference to a String object
int[] nums = {1,2,3}; // reference to an array object
Initialization and Default Values
- Local variables must be initialized before use.
- Fields get default values (0, false, null) if not explicitly set.
public class Demo {
private int count; // defaults to 0
void m() {
int x; // local
// System.out.println(x); // compile error: x not initialized
}
}
Scope and Lifetime
- Scope is bounded by the nearest braces { }.
- Local variables exist until the block ends; fields live with the object instance.
Constants with final
final
prevents reassignment. For objects, the reference can’t change, but the object may still be mutable.
final int PORT = 8080; // cannot reassign
final StringBuilder sb = new StringBuilder();
sb.append("ok"); // allowed (mutating object)
// sb = new StringBuilder(); // not allowed (reassigning reference)
Type Inference (var)
From Java 10, var
lets the compiler infer the type of local variables. It is still statically typed.
var list = new java.util.ArrayList(); // inferred as ArrayList
var total = 42; // inferred as int
Avoid overusing
var
when it harms readability. Prefer explicit types for public APIs.Shadowing and Hiding
Inner scopes can define variables that shadow outer names. Favor distinct names to reduce confusion.
int value = 10;
{
int value = 20; // shadows outer value
}
Immutability Guidelines
- Prefer
final
for fields and variables that should not change. - Use immutable data structures where possible.
Architect note: Aim for effectively final locals to simplify reasoning and enable safe lambda captures.
Try it
- Declare a
final
constant and try to reassign it (should not compile). - Create a method that uses
var
for locals and replace with explicit types. - Demonstrate local vs field default values in a small class.