Declaring a variable takes one line, but three decisions are hiding in that line. You decide what type the value is, you decide whether it is allowed to change later, and you decide what it is called. Java gives you exactly one form of type guessing, and that is the keyword var.
The previous lesson in this module covered "What Are Java's Primitive Data Types and When Do You Use Each?", and the next lesson in this module is about "How Does Type Casting and Numeric Promotion Work in Java?", which explains what happens when you mix two different types in one expression.
How do you declare a variable?
A declaration states the type and the name. A separate statement may then give it a value. Doing both at once is what you will write most of the time.
public class Variables {
public static void main(String[] args) {
int count; // declared, but not yet given a value
count = 10; // given a value
String name = "Ada"; // declared and given a value
double balance = 42.50;
boolean active = true;
System.out.println(count + " " + name + " " + balance + " " + active);
}
}
Using a local variable before it has been given a value is a compile error and not a surprise that happens later. The compiler insists that every local variable has a known value at the moment you read it. You give that guarantee up as soon as you move to fields.
When should a value be final?
A variable that is declared final can be given a value once, and then it never changes. The convention is to write such values in UPPER_SNAKE_CASE, which tells every reader that this is a constant rather than a value that simply has not changed yet.
public class Limits {
static final int MAX_RETRIES = 3;
static final String API_ROOT = "https://api.example.com";
final double taxRate; // a per-instance constant, set in the constructor
public Limits(double taxRate) {
this.taxRate = taxRate;
}
}
Three things make final worth using. The compiler stops you from assigning a new value to something that was meant to be fixed. The meaning of the constant is written down in one place instead of being implied by every place that uses it. And because a final field is set exactly once, other threads always see a steady value after the object has been built, with no extra work from you.
The keyword static is a separate idea. static means that there is one copy that the whole class shares, and final means that copy cannot change. A static final constant is the combination that most constants want.
What does var actually do?
The keyword var asks the compiler to work out the type from the value on the right. The variable still ends up with one fixed and real type. It is not a variable that can hold anything, and it cannot later hold a different type.
public class Inferred {
public static void main(String[] args) {
var name = "Ada"; // worked out as a String
var count = 42; // worked out as an int
var ratio = 0.75; // worked out as a double
// name = 42; // does not compile: the type is already fixed
System.out.println(name + " " + count + " " + ratio);
}
}
Three limits are worth remembering. var only works for local variables, and never for fields, parameters or return types. It needs a value on the right, because there is nothing to work out otherwise. And when that value is a simple literal, the type that comes out can surprise you. A decimal literal gives you a double, but a whole number literal gives you an int, which is why a loop counter written as var i = 0 is an int and not a long.
When should you use var?
Use it when the type is obvious from the right-hand side and writing the type again adds nothing. The line var now = System.currentTimeMillis(); says more with its name than it does with its type. Avoid it when the type is not obvious, because the line var result = process(data); hides the return type that the reader needs, and the version with the type written out documents the contract for free.
A good middle ground is to use var for values whose type is long and mechanical, and to write the type out whenever the type carries information.
What are the naming conventions?
- Variables, parameters and methods: use
camelCase, and start with a small letter. - Classes and interfaces: use PascalCase, and start with a capital letter.
- Constants: use
UPPER_SNAKE_CASE. - Boolean names should read like a statement, such as
isReady,hasChildrenorshouldRetry.
One word to avoid is tmp. The same is true of data and value. Those are not names, they are admissions that you did not think about the thing that you are holding. A name is the cheapest documentation that you will ever write, and a variable that has to be renamed three times in its life is telling you that the problem is not understood yet.
Where do declarations live?
A variable that is declared inside the body of a method is a local variable. It exists only while that method is running, and every call to the method gets its own copy. A variable that is declared as a field belongs to every object of the class, or to the class itself when it is static.
Fields hold the state that makes an object meaningful. They also have a life that the rest of the program can observe, so they are given stricter treatment than locals.
public class Counter {
private int total; // a field: one for every object
private static int created; // a static field: one for the whole class
public void add(int amount) {
int running = total + amount; // a local: it exists for this call only
total = running;
created++;
}
}
The difference matters for thread safety and for testing. A local variable belongs to the method and to nobody else, while a field can be changed by any code that holds a reference to the object. That is why the rule of thumb is to declare a variable as late as you can, and to prefer a local when the two choices are otherwise equal.
Quick reference
- A local variable must be given a value before you use it, and the compiler checks that for you.
- final means assign once, and static means one shared copy.
- A static final value written in
UPPER_SNAKE_CASEis the constant pattern. - var works out one fixed type from the value. It only works for locals, and it needs a value.
- The line var i = 0 gives you an int, and not a long.
- A boolean name should read like a statement.
Try it yourself: write a class with a static final currency constant, a final field that is set in the constructor, and one local variable that is declared with var. Then try to give the constant and the var a new value, and read both compiler errors carefully, because they explain two different rules.