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
Emmy
Emmy3mo ago
Declaring a variable is typically done using the type, name and optionally a value:
int someNumber = 123;
String someString = "Hello World";
long uninitializedLong;
uninitializedLong = 456;
int someNumber = 123;
String someString = "Hello World";
long uninitializedLong;
uninitializedLong = 456;
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
var someNumber = 123;
var someString = "Hello World";
//var uninitializedLong;//compile-time error because the type is unknown
//uninitializedLong = 456;
var initializedLong = 789L;

var someList = new ArrayList<String>();
var someNumber = 123;
var someString = "Hello World";
//var uninitializedLong;//compile-time error because the type is unknown
//uninitializedLong = 456;
var initializedLong = 789L;

var someList = new ArrayList<String>();
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).
List<String> explicitList = new ArrayList<>();//static type is List<String>
var implicitList = new ArrayList<String>();//static type is ArrayList<String>
var implicitListWithoutType = new ArrayList<>();//static type is ArrayList<Object>
var implicitListFromMethos = List.of("Hello", "World");//static type is List<String> because List.of returns a List
List<String> explicitList = new ArrayList<>();//static type is List<String>
var implicitList = new ArrayList<String>();//static type is ArrayList<String>
var implicitListWithoutType = new ArrayList<>();//static type is ArrayList<Object>
var implicitListFromMethos = List.of("Hello", "World");//static type is List<String> because List.of returns a List
Local variable type inference does not infer the type of lambda expression since the same lambda expression could be assigned to different types:
interface Runnable2{
void run();
}
interface Runnable2{
void run();
}
Runnable r1 = () -> System.out.println("Hello World");
Runnable2 r2 = () -> System.out.println("Hello World");

//var r3 = () -> System.out.println("Hello World");//compile-time error
Runnable r1 = () -> System.out.println("Hello World");
Runnable2 r2 = () -> System.out.println("Hello World");

//var r3 = () -> System.out.println("Hello World");//compile-time error
📖 Sample answer from dan1st
Emmy
Emmy3mo ago
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:
public void testVar(){
var localString = "This is a String"; // declaring a "String"
var localInt = 42; // declaring an "int"

System.out.println(localString);
System.out.println(localInt);
}
public void testVar(){
var localString = "This is a String"; // declaring a "String"
var localInt = 42; // declaring an "int"

System.out.println(localString);
System.out.println(localInt);
}
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
Emmy
Emmy3mo ago
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:
public class Main {
public static void main(String args[]){
var myFirstVar = 1;
var mySecondVar = "Hello, world!";
System.out.println(myFirstVar + myFirstVar);
System.out.println(mySecondVar);
}
}
public class Main {
public static void main(String args[]){
var myFirstVar = 1;
var mySecondVar = "Hello, world!";
System.out.println(myFirstVar + myFirstVar);
System.out.println(mySecondVar);
}
}
Output will be this:
2
Hello, world!
2
Hello, world!
An example of code in which all the usage rules are violated at once:
public class WrongMain {
var idk = "lol";
public static void main(String args[]){
var currentError = null;
var<var> listOfErrors = new ArrayList<>();
var lmbd = (a,b) -> (a+b);

System.out.println("Current error: ", currentError);
System.out.println("List of errors: ", listOfErrors);

error_finder(lmbd.add(2,3));
}
private void errorFinder(var error){
System.out.prinln("Hello, " + error + '!')
}
}
public class WrongMain {
var idk = "lol";
public static void main(String args[]){
var currentError = null;
var<var> listOfErrors = new ArrayList<>();
var lmbd = (a,b) -> (a+b);

System.out.println("Current error: ", currentError);
System.out.println("List of errors: ", listOfErrors);

error_finder(lmbd.add(2,3));
}
private void errorFinder(var error){
System.out.prinln("Hello, " + error + '!')
}
}
Submission from prostoblodi
Emmy
Emmy3mo ago
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.
public class VarKeyword {
public static void main(String[] args) {
var variable = 100;
System.out.println(x);
}
}
public class VarKeyword {
public static void main(String[] args) {
var variable = 100;
System.out.println(x);
}
}
However, in the following sample, our varVariable variable is going to be printed as a String.
public class VarKeyword {
public static void main(String[] args) {
var variable = "Cool Variable";
System.out.println(x);
}
}
public class VarKeyword {
public static void main(String[] args) {
var variable = "Cool Variable";
System.out.println(x);
}
}
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
Emmy
Emmy3mo ago
var keyword is used for a variable when we do not know hat type of value will be assigned to it.
ClassFirstStudentEntity obj = new ClassFirstStudentEntity();
var obj2 = new ClassFirstStudentEntity();
ClassFirstStudentEntity obj = new ClassFirstStudentEntity();
var obj2 = new ClassFirstStudentEntity();
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 -
var a = 12;
var a = 12;
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
var a,b = 3;
var a,b = 3;
. 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
Emmy
Emmy3mo ago
- 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 number = 10; // inferred as int
var name = "Alice"; // inferred as String
var list = new ArrayList<String>(); // inferred as ArrayList<String>
var number = 10; // inferred as int
var name = "Alice"; // inferred as String
var list = new ArrayList<String>(); // inferred as ArrayList<String>
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.
public class Example {
public static void main(String[] args) {
var message = "Hello, Java 10!"; // inferred as String
var count = 100; // inferred as int
var list = new ArrayList<String>(); // inferred as ArrayList<String>

System.out.println(message);
System.out.println(count);
System.out.println(list.size());
}
}
public class Example {
public static void main(String[] args) {
var message = "Hello, Java 10!"; // inferred as String
var count = 100; // inferred as int
var list = new ArrayList<String>(); // inferred as ArrayList<String>

System.out.println(message);
System.out.println(count);
System.out.println(list.size());
}
}
Submission from blue_one0102
Emmy
Emmy3mo ago
The var keyword is used to declare and define variables in a single line by inferring the type from the definition. For example:
SuperComplicatedObject superComplicatedObject = new SuperComplicatedObject();
SuperComplicatedObject superComplicatedObject = new SuperComplicatedObject();
can be made more concise and shortened as
var superComplicatedObject = new SuperComplicatedObject();
var superComplicatedObject = new SuperComplicatedObject();
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:
List list = new ArrayList();
List list = new ArrayList();
You need to specify the type explicitly, as using var would assign list as of type ArrayList
Submission from pritt_0780
Emmy
Emmy3mo ago
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
Emmy
Emmy3mo ago
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:
var variableName = initializer;
var variableName = initializer;
var message = "Hello, world!"; // infers String
var count = 42; // infers int
var list = new ArrayList<String>(); // infers ArrayList<String>
var map = new HashMap<String, Integer>(); // infers HashMap<String, Integer>
var message = "Hello, world!"; // infers String
var count = 42; // infers int
var list = new ArrayList<String>(); // infers ArrayList<String>
var map = new HashMap<String, Integer>(); // infers HashMap<String, Integer>
List<String> names = List.of("Alice", "Bob", "Charlie");
for (var name : names) {
System.out.println(name); // infers String
}
for (var i = 0; i < 10; i++) {
System.out.println(i); // infers int
}
List<String> names = List.of("Alice", "Bob", "Charlie");
for (var name : names) {
System.out.println(name); // infers String
}
for (var i = 0; i < 10; i++) {
System.out.println(i); // infers int
}
var path = Path.of("file.txt");
try (var input = Files.newInputStream(path)) {
// input inferred as InputStream
}
var path = Path.of("file.txt");
try (var input = Files.newInputStream(path)) {
// input inferred as InputStream
}
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:
var map = new HashMap<String, List<Map.Entry<String, Integer>>>(); // much cleaner than explicit type
var map = new HashMap<String, List<Map.Entry<String, Integer>>>(); // much cleaner than explicit type
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.
Emmy
Emmy3mo ago
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.
var i = 3;

// Compile error: cannot infer type: 'var' on variable without an initializer.
var j;
var obj = null;
var i = 3;

// Compile error: cannot infer type: 'var' on variable without an initializer.
var j;
var obj = null;
For use with generic types, the type parameters have to be specified either in the constructor...
var list = new ArrayList<Integer>();
var list = new ArrayList<Integer>();
or in the generic method call
var list = Utils.<String>makeList();
var list = Utils.<String>makeList();
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:
for (Map.Entry<Integer, String> entry : map.entrySet()) {
// ...
}
for (Map.Entry<Integer, String> entry : map.entrySet()) {
// ...
}
The usage of var here is convenient to avoid the long type of the iterator variable.
for (var entry : map.entrySet()) {

}
for (var entry : map.entrySet()) {

}
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
Emmy
Emmy3mo ago
- 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
Emmy
Emmy3mo ago
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:
String s1 = "This string";
var s2 = "This string";
String s1 = "This string";
var s2 = "This string";
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:
var foo;
if (someCondition) {
foo = 42;
}
var foo;
if (someCondition) {
foo = 42;
}
So var is only appropriate in situations where the variable can be declared and initialized at the same time.
Emmy
Emmy3mo ago
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:
public interface Foo {}

public class Bar implements Foo {}

public class Baz implements Foo {}

public class VarExample {

public static void main(String[] args) {

var foo = new Bar(); // type of `foo` is `Bar`, not `Foo`
useAFoo(foo); // OK!
foo = new Baz(); // ERROR: incompatible types: Baz cannot be converted to Bar
}

private static void useAFoo(Foo foo) {
// ...
}
}
public interface Foo {}

public class Bar implements Foo {}

public class Baz implements Foo {}

public class VarExample {

public static void main(String[] args) {

var foo = new Bar(); // type of `foo` is `Bar`, not `Foo`
useAFoo(foo); // OK!
foo = new Baz(); // ERROR: incompatible types: Baz cannot be converted to Bar
}

private static void useAFoo(Foo foo) {
// ...
}
}
Submission from dangerously_casual

Did you find this page helpful?