EMZETT.
Login

var Keyword

In short: A keyword for declaring a variable, where the data type isn’t explicitly stated but automatically inferred by the compiler from the assigned value (“type inference”).

In more detail: var saves typing for obvious types (var number = 5; instead of int number = 5;), but doesn’t change type safety at all — the type is just as fixed after assignment as with an explicit declaration, it’s just determined automatically instead of written by the developer. In Java, var has existed since version 10; in JavaScript, var has a different, older meaning (largely replaced by let/const).

In Depth

var number = 5;              // recognised by the compiler as int
var text = "Hello";          // recognised by the compiler as String
var list = new ArrayList<String>(); // recognised as ArrayList<String>
 
// number = "now a text"; // compiler error - the type is fixed, just not spelled out

Important to understand: var in Java is purely a compile-time convenience, not dynamic typing like in Python or JavaScript. The compiler internally replaces var immediately with the actual, concrete type (here int, String, ArrayList<String>) — at runtime, var no longer exists at all, and the compiled bytecode looks identical to if you had written out the type by hand. var only works for local variables with immediate initialisation, not for class fields, method parameters, or return types — the compiler has to be able to infer the type from the assigned value, and that’s only possible right at the declaration.

The meaning differs fundamentally from JavaScript’s var: there, var has denoted a variable with function scope (instead of block scope) since the early days of JS, and has NOTHING to do with type inference — JavaScript is dynamically typed anyway, and any variable can change its type at any time. Modern JavaScript codebases now avoid var almost entirely in favour of let and const, which offer cleaner block scoping. Anyone switching between Java and JavaScript should therefore be aware: same name, completely different concept.

See also: Declaring Variables