Java 10 Var Keyword
The var keyword, which allows local variable type inference, was introduced in Java 10. It lets us specify local variables and allows the compiler to find out what type of variable they are based on initialization rather than needing to specify it directly.
Important Points
- The compiler implies a variable's type from the value it is assigned during the initialization.
- Only local variables used in methods, loops, or other local scopes are allowed to use var. It is not applicable to method parameters or fields in classes.
- The variable needs to be initialized simultaneously with its declaration using var.
Syntax:
var a=29;
Example 1: Declaring any datatype with the var keyword.
Filename: VarDatatype.java
import java.util.ArrayList;
public class VarDatatypes
{
public static void main(String[] args)
{
var a = 29;
System.out.println("Age: " + a);
var pi = 3.14159;
System.out.println("Pie Value: " + pi);
var txt = "Var Keyword";
System.out.println("Message: " + txt);
var numbers = new int[]{1, 2, 3, 4, 5};
System.out.print("Numbers: ");
for (var num : numbers)
{
System.out.print(num + " ");
}
System.out.println();
var names = new ArrayList<String>();
names.add("Var");
names.add("Java 10");
System.out.print("Var: ");
for (var name : names)
{
System.out.print(name + " ");
}
System.out.println();
}
}
Output:
Age: 29
Pie Value: 3.14159
Message: Var Keyword
Numbers: 1 2 3 4 5
Var: Var Java 10
Example 2: Declaring var using a local variable.
Filename: VarLocal.java
public class VarLocal
{
public static void main(String[] args)
{
var txt = "It is a Local Variable";
System.out.println(txt);
var numbers = new int[]{29, 31, 16, 20, 23};
System.out.print("Numbers: ");
for (var num : numbers)
{
System.out.print(num + " ");
}
System.out.println();
}
}
Output:
It is a Local Variable
Numbers: 29 31 16 20 23
Inferred Typing in Var Keyword:
When a local variable declaration uses the var keyword, the compiler can infer the type of the variable based on its initialization value. It is known as inferred typing. When we declare a variable with var, this provides the compiler access to determine its type during initialization by looking at the assignment's right-handed side. It is compared with dynamically typed languages, such as Python or JavaScript, where a variable's type may change while the program is running. The inferred type in Java is a component of the static typing system and is still known at compile time.
Reducing boilerplate code without losing the benefits of static typing, type safety, and readability is the aim of inferred typing by using var. Var must be used effectively, however, particularly while clearly defining the kind could improve the readability of the code.
Example:
var age = 29; // inferred as int
var pie = 3.14159; // inferred as double
var txt = Var Keyword; // inferred as String
Uses of Var Keyword:
- Var decreases code by removing unnecessary repetition and specific type declarations when the type indicates from the context.
- Using var allows the purpose of a variable to take priority instead of its type when variable names are descriptive.
- Var may also help refactoring by eliminating the need for specific type declarations, particularly while making changes to complex types or longer type names.
- Var can adjust to new types inferred from reassignments or initializations while the code is modified or changed.
Benefits of Var Keyword:
- Var shortens code and minimizes lines of code by assuming types from initialization, hence reducing redundancy.
- It can lessen repeated type declarations in code, especially for basic initializations, making it easier to read.
- Makes code easy to read and compact, mainly while working with complex types or generic collections.
- Improves the priority of enhanced for-loops at the iteration logic by reducing noise.
When to not use Var Keyword:
- Code clarity and maintenance may be impacted if variables are reassigned to different types or if the initialization values are of various types.
- Var cannot be used for fields in classes or as a parameter in methods. In some cases, specific typing is required.
- Var should not be used for fields inside of classes. Specific type in fields is generally helpful for maintainability and readability.
Conclusion:
In some cases, Java's var keyword is a useful feature that helps code simplify and improves clarity. When used effectively, it can maintain Java's type safety and static typing while producing code that is shorter and more expressive. Deciding to utilize var should always put maintainability and code clarity first, finding a balance between short and clear, creating standards and specific type declarations for clarity.