Nanfeng

Notes on software development, code, and curious ideas

Variables in Java

A variable associates a name and type with a value that a program can read or change.

Declaration and initialization

1
2
3
4
5
int age;
age = 18;

String name = "Ada";
double width = 12.5, height = 8.0;

Java is statically typed, so the declared type determines which values and operations are allowed. var can infer a local variable’s compile-time type from its initializer:

1
var message = "Hello"; // Inferred as String

Local variables

Variables declared inside a method, constructor, or block are local to that scope:

1
2
3
4
5
void printTotal(int quantity) {
double price = 9.99;
double total = quantity * price;
System.out.println(total);
}

Local variables must be definitely assigned before use. Their lifetime ends when execution leaves the relevant scope.

Parameters

Method and constructor parameters receive values from the caller and behave like initialized local variables:

1
2
3
int add(int left, int right) {
return left + right;
}

Java passes arguments by value. For an object, the copied value is the object reference.

Instance fields

An instance field belongs to each object:

1
2
3
4
class Player {
private String name;
private int score;
}

Every Player has its own name and score. Fields receive default values if no initializer is supplied.

Static fields

A static field belongs to the class and is shared by all instances:

1
2
3
class Player {
static int playerCount = 0;
}

Constants

final prevents reassignment. Constants are commonly static final and use upper snake case:

1
private static final int MAX_RETRIES = 3;

For ordinary names, use descriptive lower camel case such as currentScore. Avoid Java keywords, leading digits, and names that differ only by capitalization.

+