Sub topic 1
Starting point: explicit types in Java
Before you can judge what var changes, you need a precise picture of what Java does without it. This chapter reviews how static typing works for local variables and how explicit declarations behave. It also shows where the repetition in those declarations comes from. Later chapters build on this.
Prerequisites
This chapter assumes you can already do the following:
- Write and compile a small Java program with a
mainmethod. - Declare local variables and tell primitive types (
int,double,boolean) from reference types (String,List<String>). - Read generic types such as
Map<String, List<Integer>>at a basic level. - Recognize an enhanced
forloop and atry-with-resourcesstatement.
To run the examples, use any JDK. The var keyword needs JDK 10 or later, and later chapters rely on that.
What static typing means
Java is statically typed. Every variable and every expression has a type that the compiler can determine before the program runs. The compiler uses these types to check your code:
- Assignments must be type-compatible.
- Method calls must name a method that exists on that type.
- Operators must be applied to operands that support them.
If a check fails, the program does not compile, so the error cannot reach production. This is the property you must keep in mind throughout the tutorial: var does not give this up.
Static typing is separate from how much you write. A language can be statically typed and still let you omit type names, because the compiler works the types out itself. Java has always done this for expressions, for example in a + b. Until Java 10 it did not do it for local variable declarations.
Explicit local variable declarations
A local variable is a variable declared inside a method, constructor, or block. Its declaration has three parts: a type, a name, and usually an initializer.
public class ExplicitTypes {
public static void main(String[] args) {
int count = 10;
String name = "Ada";
double ratio = 0.75;
boolean ready = true;
count = count + 1;
// count = "eleven"; // does not compile: String cannot be converted to int
System.out.println(name + " " + count + " " + ratio + " " + ready);
}
}This prints Ada 11 0.75 true. The type written on the left fixes what the variable can hold for its whole lifetime. The commented-out assignment shows the compiler enforcing that.
Compatibility rules the compiler applies
Assignments follow a few rules you should know well, because inference interacts with them later.
| Assignment | Compiles? | Reason |
|---|---|---|
| `long big = 5;` | Yes | Widening: `int` converts to `long` automatically. |
| `int small = big;` | No | Narrowing from `long` to `int` needs an explicit cast. |
| `int small = (int) big;` | Yes | The cast states that you accept possible loss. |
| `double d = 3;` | Yes | Widening from `int` to `double`. |
| `int i = 3.5;` | No | A `double` literal cannot narrow to `int` implicitly. |
| `byte b = 10;` | Yes | A constant that fits in `byte` is allowed by a special rule. |
| `Object o = "text";` | Yes | A `String` is an `Object`. |
| `String s = new Object();` | No | An `Object` is not necessarily a `String`. |
Notice the byte b = 10; row. The literal 10 is an int, yet the assignment compiles. That special rule applies only to compile-time constants, and it matters again when we look at literals and var.
Declaration and initialization are separate steps
Java lets you declare a local variable without a value, as long as every path assigns it before the first read. This rule is called definite assignment.
public class DefiniteAssignment {
public static void main(String[] args) {
int limit; // declared, not yet assigned
if (args.length > 0) {
limit = Integer.parseInt(args[0]);
} else {
limit = 5;
}
System.out.println("limit = " + limit); // limit = 5 when run with no arguments
}
}If you delete the else branch, the compiler reports that limit might not have been initialized. Unlike fields, local variables never receive a default value such as 0 or null.
This split form is legal with an explicit type because the type is written down and needs no initializer. You will see in a later chapter that var cannot do this, since it reads the type from the initializer.
Declared type versus runtime type
A variable of reference type has two types that are easy to mix up:
- The declared type is what you write on the left. The compiler uses it to decide which members you may use.
- The runtime type is the class of the object the variable refers to when the program runs.
They are often different, and polymorphism depends on that.
import java.util.ArrayList;
import java.util.List;
public class DeclaredVsRuntime {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ada");
names.add("Grace");
System.out.println(names.size()); // 2
System.out.println(names.getClass().getName()); // java.util.ArrayList
// names.ensureCapacity(100); // does not compile: List has no such method
ArrayList<String> concrete = new ArrayList<>();
concrete.ensureCapacity(100); // compiles: ArrayList declares it
System.out.println(concrete.size()); // 0
}
}The first variable is declared as List<String> but refers to an ArrayList object. The compiler only lets you call methods that List declares. The runtime type is ArrayList, which the getClass() call confirms, but the compiler does not use that knowledge for the check. The second variable is declared as ArrayList<String>, so ensureCapacity is available.
Programming to the interface, such as declaring List and not ArrayList, is a long-standing Java habit. It keeps code flexible, because you can change the implementation on the right without touching later code. An explicit declared type is therefore a design decision, not just a formality. Remember this when we reach the chapter on inferred versus declared types, where var takes the right-hand type instead.
Where the repetition comes from
Look at a declaration with a generic type.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Verbose {
public static void main(String[] args) {
Map<String, List<Integer>> scoresByStudent = new HashMap<String, List<Integer>>();
List<Integer> adaScores = new ArrayList<Integer>();
adaScores.add(90);
adaScores.add(85);
scoresByStudent.put("Ada", adaScores);
for (Map.Entry<String, List<Integer>> entry : scoresByStudent.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}This prints Ada -> [90, 85]. The type Map<String, List<Integer>> is written three times in just a few lines: on the left of the declaration, on the right inside new HashMap<...>, and again in the loop variable. Only the first is a choice you made. The others restate what the compiler already knows from the right-hand side or from entrySet().
Java has reduced this repetition in steps:
- Java 5 introduced generics, which added type arguments to every declaration.
- Java 7 introduced the diamond operator
<>, so the type arguments on thenewexpression can be left out. You can writenew HashMap<>(). - Java 10 introduced
varfor local variables, which lets you leave out the type on the left as well.
Here is the same code as it would be written with the diamond only.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Diamond {
public static void main(String[] args) {
Map<String, List<Integer>> scoresByStudent = new HashMap<>();
List<Integer> adaScores = new ArrayList<>();
adaScores.add(90);
scoresByStudent.put("Ada", adaScores);
System.out.println(scoresByStudent); // {Ada=[90]}
}
}The diamond works because the compiler infers the type arguments from the declared type on the left. This is inference flowing from left to right. var reverses the direction: the compiler reads the right side and fills in the left. Keeping this direction in mind explains several surprises you will meet later, such as what new ArrayList<>() means when there is no left-hand type to read.
The cost of explicit types
Repetition is not the only issue. Long declarations also have these effects:
- They push the variable name far to the right, where it is harder to scan.
- They add noise when the type is obvious from the initializer, as in
String name = new String(...)orPerson p = new Person(). - They add edit work when you change a type, since the name appears in several places.
Explicit types also have real benefits, and a good deal of this tutorial is about weighing them:
- The type is visible at the declaration, even when the initializer is a method call whose return type you have to look up.
- The declared type can be a deliberately general type, such as an interface.
- Splitting declaration from assignment is possible.
Common errors with explicit declarations
These are the mistakes you are most likely to meet at this stage. Knowing the messages helps later, because var produces related ones.
- Incompatible types. Assigning a value of a type that does not convert to the declared type, such as
int n = "5";. The compiler reportsincompatible types. - Lossy conversion. Assigning a
longordoubleto anintwithout a cast. The message mentionspossible lossy conversion. - Use before assignment. Reading a local variable on a path where it was not assigned. The message is
variable might not have been initialized. - Calling a method the declared type lacks. For example, calling
ensureCapacityon aList. The message iscannot find symbol, even though the object at runtime would support the call. - Redeclaring a name in the same scope. Declaring
int counttwice in one method producesvariable count is already defined.
The fourth error is the one to remember. It shows that the compiler decides by the declared type, never by what the object happens to be at runtime.
Summary of what carries forward
Keep these points as the baseline for the rest of the tutorial:
- Every local variable has one static type for its whole life, and the compiler checks every use against it.
- For reference types, the declared type and the runtime type can differ, and only the declared type controls which members you may use.
- Explicit declarations repeat information the compiler can often derive, and the diamond operator removes only some of that repetition.
- The type on the left of a declaration is a design choice. It can be an interface that hides the implementation.
Exercise
In the following code, which line does not compile, and why? Would the line compile if the variable items were declared as ArrayList<String>?
List<String> items = new ArrayList<>();
items.add("x");
items.trimToSize();
Show answer
The line items.trimToSize(); does not compile. The compiler checks the call against the declared type List<String>, and List has no trimToSize method, so it reports cannot find symbol. The object created at runtime is an ArrayList, but that does not matter for the check. If items were declared as ArrayList<String>, the call would compile, because ArrayList declares trimToSize().
Exercise
Why does this code fail to compile, and what is the smallest change that makes it compile and print 7? public class Demo { public static void main(String[] args) { int total; if (args.length > 5) { total = 7; } System.out.println(total); } }
Show answer
The compiler cannot prove that total is assigned on every path. When args.length is 5 or less, the if body is skipped, so println could read an unassigned local variable, and the compiler reports variable total might not have been initialized. Local variables have no default value. The smallest fix is to assign on every path, for example by changing the declaration to int total = 7; or by adding an else { total = 7; } branch. Either way every path assigns total and the program prints 7.