The reserved keywords in Java are predefined and can not be used as a variable, object, or any other identifier. These keywords are referred to as “reserved” because they belong to the Java syntax. If any of the reserved keywords is used in the code, the output results in an error. Some of the reserved keywords in Java are interface, void, return, extend, implement, var, etc.
We will comprehensively discuss the var keyword in this article using the following content:
- What is the var keyword in Java?
- The Var keyword is implemented on Different data types.
- ‘Var’ keyword in Loop
- ‘Var’ keyword and the Collections in Java
- Removal of Duplication using the Var keyword
- Errors while working with the Var keyword
- Conclusion
What is the var Keyword in Java?
The ‘var’ keyword was introduced in Java version 8. This keyword doesn’t require the datatype to be explicitly provided instead it considers what datatype is declared as the variable using the initials of the declared value. For example var x = 15; already predicts that the data type is integer without explicitly declaring the type.
The var Keyword on Different Datatypes
The ‘var’ keyword in Java declares any datatype be it a string, integer, float, etc without defining the type of data provided. The code below shows the example that implements the var keyword in Java.
class VarExample1 {
public static void main(String[] args) {
// String
var s = "Java";
System.out.println("The String:" + s);
// Integer
var p = 125;
System.out.println("The Integer:" + p);
// Boolean Value
var q= true;
System.out.println("The Boolean :" + q);
// Float
var t = 0.001;
System.out.println("The Float is:" + t);
//L = Long data type
var l = 8963L;
System.out.println("The Long Data type:" + l);
}
}
In the above code block:
- The class is declared as the initial step of code in Java.
- In the next step, the different datatypes are declared without explicitly defining them.
- The output is printed to observe the effect of the var keyword in Java.
Output
The output shows that the values of different types in Java are declared using the var keyword.
Use of ‘Var’ Keyword in for Loop
The var keyword can be applied in the for loop initialization where the “int” is usually declared. The code below shows the implementation of the var keyword in the for loop.
class VarExample2 {
//Declare the Main class of Java
public static void main(String[] args)
{
System.out.println("The numbers are: ");
//for loop to print the numbers from 1 to 3
for (var x = 1; x <= 4; x++) {
System.out.println(x);
}
}
}
In the above Java code:
- The for loop contains the keyword “var” instead of “int” to utilize the integer data type.
- The for loop executes four times and prints the variable by utilizing the println() method.
Output
The output below shows that there is no difference when ‘var’ is used instead of ‘int’. The result generated is the same.
Use of ‘Var’ Keyword in Collections
The var keyword can also be used to simplify the complex structure of the collection framework in Java as depicted in the code below.
import java.util.List;
class VarExample {
//Declare the Main class of Java
public static void main(String[] args){ var m = List.of("Hello", "Java");
System.out.println(m);
}
}
In the above code block:
- The elements to the list are added using the List.of() method and the results are stored in the variable m that is declared using the var keyword.
- The output list is printed.
Output
The output shows that the elements of the list are printed as per the input.
Use of ‘Var’ Keyword to Remove Duplicate Values
The var keyword in Java is found to be very helpful in elimination of the duplicate values as suggested by the code below.
public class VarExample1 {
// main() method of Java
public static void main(String args[])
{ //Declare the Strings
String S = new String("Programming in Java");
System.out.print("The Output by declaring data type is: " + S);
var v = "Programming in Java";
System.out.print("The Output by using 'var' is: " + v);
}
}
In the above code block:
- The string “S” is declared as “Programming in Java” and the output is printed.
- The string is also declared using the var keyword of Java without any duplication of the data type.
Output
The output below shows that both the outputs are the same.
Errors While Working with the Var Keyword
There are certain areas of Java programming where the var keyword can not be implemented. In such cases, if the keyword is implemented it throws an error when the program is executed. The list of the errors is depicted below.
- If the var keyword is assigned globally
- Var keyword on generic type
- Var keyword on the return type and method parameters
- Var Keyword without Initialization
- Declaration of Null in Var
- Var can not be explicitly implemented on the Lambda Expression
Error 1: If the var keyword is assigned globally
The var keyword in Java can not be assigned globally as shown in the code below.
//Declare the class
public class VarError1 {
// main() method of Java
var v = "Java";
public static void main(String args[])
{
System.out.print("The Output by using 'var' is: " + v);
}
}
In the above code block:
- The class is declared as “VarError1” and the string is declared using the ‘var’ keyword.
- This string is declared outside the main class of Java which means it is assigned globally.
Output
The output shows that the ‘var’ keyword can not be assigned at that specific place in the code.
Error 2: Var on Generic Type
The code below states that the following way of implementing the var keyword generates an error.
//Import the package
import java.util.*;
class VarExample2 {
public static void main(String[] args)
{ // Generic type
var<Integer> li = new ArrayList<Integer>();
// add elements
li.add(52);
li.add(32);
li.add(99);
// print the list
System.out.println(li);
}
}
In the above code block:
- The var keyword is declared with the Integer data type which is the wrong format. Since the var keyword knows what data type is declared without explicitly defining it.
Output
The output below shows that the integer is an illegal reference to the var type.
Correct Method
The example below elaborates on the correct way to use the var keyword.
//Import the package
import java.util.*;
class VarExample2 {
public static void main(String[] args)
{ // Generic type
var li = new ArrayList<Integer>();
// add elements
li.add(52);
li.add(32);
li.add(99);
// print the list
System.out.println("The Output is:" + li);
}
}
In the above code:
- The var keyword is declared without the data type.
- The integer list is printed to the output.
Output
The output shows that the integer list is printed using the var keyword.
Error 3: Var keyword on the Return Type and Method Parameters
The var keyword can not be used with the return type and the method parameters in Java as shown in the code below.
// Java class
class VarError3 {
var firstclass() {
return ("The first class in Java"); }
void secondclass(var a) {
System.out.println(a); }
//The main() method
public static void main(String[] args)
{
VarError3 v3 = new VarError();
var v = obj.firstclass();
obj.secondclass();
}
}
In the above code block:
- The ‘var’ keyword is used as a return type for the “firstclass() method”.
- The ‘var’ keyword is declared in the “secondclass()” method.
- In the main() method, the objects are declared to print the outcomes.
Output
The output below shows that the “var” keyword can not be declared as a return type nor as a method in Java.
Error 4: Var Keyword without Initialization
The var keyword in Java can not be declared without initialization. This keyword needs to be initialized with some value to continue the execution of code.
//Import the Package
import java.io.*;
//Declare the class
class VarError4{
public static void main(String[] args)
{
//'var' is declared without initialization
var result;
}
}
In the above code block:
- The class is created as “VarError4” in Java.
- In the main() method, the var keyword “ result ” is declared without initialization.
Output
The output below shows that the keyword throws an error if it is not initialized properly.
Error 5: Declaring a Null Value to the Var Keyword
The code example below depicts how the “var” keyword” behaves when “null” is declared to it.
//Import the Package
import java.io.*;
//Declare the class
class VarError5{
public static void main(String[] args)
{
//'var' is declared null
var result = null;
}
}
In the above code block:
- The var keyword is initialized with a “null” value.
- The output is printed accordingly.
Output
The output below shows that the “null” can not be used to initialize the var keyword in Java.
Error 6: Var can not be explicitly implemented on the Lambda Expression
The code below shows that the var keyword in Java can not be implemented on the lambda expressions.
interface Sum{
int sum(int a, int b);
}
//Declare the class
public class VarError6 {
public static void main(String[] args){
var result = (a,b)-> a+b;
int output = result.sum(15, 2);
System.out.println(output);
}
}
In the above code block:
- The interface is declared as “Sum” along with the integers declared as “a” and “b”.
- The class is declared using the “public” keyword.
- The lambda expression is declared without an explicit target type.
- The output is printed according to the input.
Output
The output below shows that the lambda expression in Java requires an explicit target-type in Java.
Correct Method of Implementing the Lambda Expression Using the var keyword
The code below shows the correct implementation of the var keyword on the Lambda expressions in Java.
interface Sum{
int sum(int a, int b);
}
//Declare the class
public class VarError6 {
public static void main(String[] args){
Sum result = (var a, var b)-> a+b;
int output = result.sum(15, 2);
System.out.println("The Sum is:" + output);
}
}
In the above code block:
- The var keyword is used as compared to the previous example where “int” was defined.
Output
The output is printed as the sum of numbers specified at the input.
This concludes the working of the “var” keyword in Java.
Conclusion
The var keyword in Java is a way to declare different datatypes in Java without explicitly defining these datatypes. In this article, we have discussed the implementation of the var keyword in Java with different scenarios along with the errors while working with it.