Week 130 — What is the `var` keyword and how can one use it?
Question of the Week #130
What is the
var
keyword and how can one use it?13 Replies
Declaring a variable is typically done using the type, name and optionally a value:
For local variables, it is also possible to use the keyword
var
instead of the type name if the type can be inferred from the value. This works only if the variable is assigned at the declaration
This feature is called local variable type inference.
While explicitly specifying the type allows using different types for the variable and the value, this is not possible with var
. Furthermore, creating a generic object will use the most general type (e.g. Object
).
Local variable type inference does not infer the type of lambda expression since the same lambda expression could be assigned to different types:
📖 Sample answer from dan1st
The var keyword in java ensures flexibility for declaring local variables. It allows you to declare a variable without explicitly specifying its type e.g., int, String, float, other classes, etc. When the program is compiled; the compiler will then decide/figure out, what type the var variable is -> based on the assigned value.
An example of its usage:
This feature was introduced to make the code cleaner and more readable. However, I personally think that the var variable makes code a bit difficult to read, especially if the type isn't obvious. For this reason I usally avoid it.
For more examples see below:
https://www.geeksforgeeks.org/var-keyword-in-java/
Submission from cfj1211
This keyword allows you to declare a variable without specifying its type. It cannot be used to create a global variable, cannot list with the generic type, and cannot be used in lambda. Also, this keyword cannot declare a variable if it has no value initially. It also cannot be used as an argument in methods and cannot be returned. It cannot contain null.
Example of use:
Output will be this:
An example of code in which all the usage rules are violated at once:
Submission from prostoblodi
The
var
keyword can be used to automatically infer a variable's datatype.
How Can We Use This?
- We can use the var keyword to make our code more readable, less verbose and easier to refactor.
Examples
In the following sample, our varVariable
variable is going to be printed as an int
.
However, in the following sample, our varVariable
variable is going to be printed as a String
.
Limitations Of The var
Keyword
1. We can only use var
in a local scope, in simpler terms, it must only be defined within the method level, not the class level.
2. We can't use var
as a generic type, meaning no List<var>
.
3. var
variables must be initialized and not null
.
4. var
cannot represent a lambda function.Submission from skywolfxp.dev
var keyword is used for a variable when we do not know hat type of value will be assigned to it.
var needs to be declared and initialized in the same line. Doing declaration in one line and then initializing in another line will lead to an error because the data type of var is determined at runtime.
if we write this -
then a will get data type of int.
* var cannot be assigned null when it is first declared. but once initialized, it can be made null.
* var cannot be used in constructor, method parameters or instance variables. it can be used only in local scope.
* Also we can't write this . This is not acceptable and will lead to compilation error.
* Since var is not a reserved keybword, it can be used as identifier.
Submission from all_might9678
- What is the
var
keyword?
var
keyword is a local variable type inference.
It allows developers to declare local variables without explicitly specifying their type, letting the compiler infer the type from the assigned value.
-How to use?
var
can only be used for local variables inside methods, constructors, or initializer blocks. It cannot be used for fields (class variables), method parameters, or return types.
The compiler infers the variable’s type based on the initializer expression. For example, var x = 5;
infers int.
Must initialize the variable at the time of declaration. You cannot write var x;
without assigning a value.
Despite using var
, the variable is still statically typed. The inferred type is fixed and cannot change.
Especially useful when the type is obvious or very verbose, such as when working with generics.
Submission from blue_one0102
The
var
keyword is used to declare and define variables in a single line by inferring the type from the definition. For example:
can be made more concise and shortened as
Note that the type is automatically inferred from the expression on the right side of the the assignment operator. While this is convenient at times, there are moments where you do not want the type on the right to be the type of your variable. A good example of this is when you're using interfaces:
You need to specify the type explicitly, as using var
would assign list
as of type ArrayList
Submission from pritt_0780
The var keyword allows to initialize a variable without declaring its type. For example:
var num = 15;
System.out.println(num);
This prints 15 as an integer type.
Submission from markdev123456
var
is a reserved type name, introduced in Java 10, that enables local variable type inference.
Local variable type inference means you can declare a local variable without explicitly specifying it's type. The Java Compiler automatically infers the type from the initializer on the right-hand side at compile time.
Syntax:
When to use (and not use) var
The var
keyword is generally used when the type is obvious from the initializer. It helps to reduce verbosity, especially with complex generic types.
Example:
You should above var
when:
- The initializer is complex or unclear, making code harder to read.
- For primitives if it reduces clarity (e.g., var x = getValue();
what type is x
?).
- When declaring fields, method parameters, or return types (not allowed by the compiler, java is not python!!).
Key Points To Remember When Using var
- var
is not a true Java keyword, but a reversed type name. You cannot use var
as a class or interface name, but you can technically still use it as a variable name (in some context).
- Inferred type is determined at compile time and cannot change after declaration.Java as a statically typed language checks the type of every variable at compile time and makes sure that their values correspond to the type they were declared as.
However, being statically typed does not prevent Java from taking advantage of local variable type inference, which allows the Java language to infer the type of a variable based on the value that it is assigned to.
The
var
keyword allows us to omit the explicit type declaration of a local variable when it is declared and assigned at the same time.
For use with generic types, the type parameters have to be specified either in the constructor...
or in the generic method call
otherwise, the generic type will default to Object
.
var
is useful to avoid having to type long type names or generic types with a lot of type parameters. For exampe, often times we find ourselves looping through the entires of a map:
The usage of var
here is convenient to avoid the long type of the iterator variable.
It is recommended to avoid using var
when the type of the initializer expression is not clear. While it is acceptable to use var
for variables initialized with a constructor, it is not that recommended for variables with initializers which consist of a method whose return type is not clear based on the name, as it hurts code clarity and readability.⭐ Submission from arkosammy12
-
var
cannot be used for fields, parameters or return types.
- It also cannot be used without an initializer, or with null
as the initializer, as this is ambiguous and compiler would not be able to infeer the type.
- The inferred type is always the actual type of the initializer, not a supertype or a interface.
- You should ise descriptive variable names to maintain readability, since the explicit type is hidden when using var
.⭐ Submission from daysling
var
provides a more concise syntax for declaring a new variable by allowing the compiler to infer the type from the right-hand expression. For instance, both of these variable declarations are equivalent:
s1
and s2
both have the type String
and contain the value This string
.
While saving a few keystrokes, var
should be limited to use in places where the inferred type is obvious. Otherwise, readers of the code will have a hard time understanding what type the variable is.
var
can only be used to declare local variables inside methods. Fields and method parameters cannot be declared with var
.
Also, because the type must be inferred at the declaration point, the variable must immediately be assigned. The following example will not compile:
So var
is only appropriate in situations where the variable can be declared and initialized at the same time.Finally, it's important to note that
var
does not declare a "dynamically-typed" variable. The type inferred by the compiler becomes the static type of that variable for its entire scope. In polymorphic cases, this may not be what you want:
Submission from dangerously_casual