#Static types and var
AddedIn TypeScript, types are a layer on top of JavaScript: the compiler checks them, then erases them, and at run time every value is just a JavaScript value. In Java, types are the language itself. Every variable, field, parameter and return value has a type the compiler knows, and every object also carries its class at run time. There is no "turn the checker off" switch, no any, and a cast is checked by the JVM when it runs, not just believed.
var (Java 10) doesn't change any of that. It only means "compiler, work out the type from the right-hand side". var count = 10; declares an int, exactly as if you'd written int count = 10;, and from then on count can only hold ints. That's the same as TypeScript's let count = 10 inferring number. What Java has no equivalent of is the escape hatch: TypeScript's any turns checking off, while Java's closest thing, Object, forces you to cast back before you can use the value.
The mental model: a Java variable is a box with a label printed on it at compile time. var lets the compiler print the label for you; it never makes the label erasable.
void main() {
var count = 10; // int
var price = 19.99; // double
var name = "Rohit"; // String
var tags = new ArrayList<String>(); // ArrayList<String>
tags.add("java");
count = count + 5;
IO.println(count + " " + price + " " + name.toUpperCase() + " " + tags);
Object anything = name; // you can store anything in an Object…
String back = (String) anything; // …but you must cast to use it again
IO.println(back.length());
}void main() {
var count = 10;
count = "ten";
}$ java Infer.java
15 19.99 ROHIT [java]
5
$ java Broken.java
Broken.java:3: error: incompatible types: String cannot be converted to int
count = "ten";
^
1 error
error: compilation failed- Each
vargets its type from its initialiser:10is anintliteral,19.99adouble,"Rohit"aString, andnew ArrayList<String>()anArrayList<String>. The compiled bytecode is identical to writing the types out. count = count + 5is fine (anintstays anint), so the first line prints15 19.99 ROHIT [java].name.toUpperCase()compiles because the compiler knowsnameis aString.Object anything = nameworks because every class extendsObject. Butanything.length()wouldn't compile: the label on the box saysObject, andObjecthas nolength(). The cast(String) anythingchanges the label back, and the JVM checks at run time that the object really is aString. It is, soback.length()prints5.Broken.javatries to put aStringinto theintbox. The compiler refuses with "incompatible types: String cannot be converted to int" and nothing runs. In JavaScript,let count = 10; count = "ten";is fine; in TypeScript it's the same error as here, but TypeScript would still emit the JavaScript if you let it.- So
varis about less typing, not less typing-safety: the type is still fixed, just inferred.
A TypeScript as is a promise to the compiler and costs nothing at run time; if you lie, the code carries on with the wrong value. A Java cast is checked by the JVM, and a wrong one fails on the spot with ClassCastException.
void main() {
Object value = 42;
IO.println(value.getClass().getName());
String text = (String) value;
IO.println("never printed: " + text);
}$ java Cast.java
java.lang.Integer
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
at Cast.main(Cast.java:4)Object value = 42stores anIntegerobject (theintis boxed; see the next topic). The variable's compile-time type isObject, but the object itself still knows its class:getClass().getName()printsjava.lang.Integer.(String) valuecompiles, because anObjectmight be aString. At run time the JVM checks the real class, finds anInteger, and throwsClassCastExceptionwith a message naming both classes. The program stops there, as it's meant to on this page.- The TypeScript equivalent,
const text = value as string, would compile and thentext.lengthwould quietly beundefined. Java's types survive to run time, which is also whyinstanceofworks on any class (chapter 05). The one exception is generic type arguments, which are erased (chapter 04).
var is for local variables with an initialiser (and the variables of for loops and try-with-resources). It isn't allowed on fields, method parameters or return types, and it can't infer from null or from a lambda on its own. Each of these is a compile error:
void main() {
var later;
var nothing = null;
var square = (int x) -> x * x;
}var total = 0;
void main() {
IO.println(total);
}$ java Limits.java
Limits.java:2: error: cannot infer type for local variable later
var later;
^
(cannot use 'var' on variable without initializer)
Limits.java:3: error: cannot infer type for local variable nothing
var nothing = null;
^
(variable initializer is 'null')
Limits.java:4: error: cannot infer type for local variable square
var square = (int x) -> x * x;
^
(lambda expression needs an explicit target-type)
3 errors
error: compilation failed
$ java Field.java
Field.java:1: error: 'var' is not allowed here
var total = 0;
^
1 error
error: compilation failedvar later;has no initialiser, so there's nothing to infer from.var nothing = null;fails becausenullhas no useful type of its own.var square = (int x) -> x * x;fails because a lambda needs a target type, a functional interface such asIntUnaryOperator(chapter 08), andvardoesn't provide one.- The compiler reports all three, each with its own message, and nothing runs.
- In
Field.java,var total = 0;sits outsidemain, so in a compact source file it's a field of the implicit class, and fields must have a declared type: "'var' is not allowed here". These limits are deliberate:varsaves you repeating a type that's obvious from the same line, and nothing else.