JDK 10 introduced various new features, the most visible enhancement among them was the introduction of Java local inference of variables. It is a feature that allows Java developers to skip the type declaration associated with local variables. It is usually defined inside method definitions, initialization blocks, for-loops, and other blocks like if-else, and the type is inferred by the JDK. With Java local interference, the data type will, then, be decided by the compiler at compile-time, based on the data assigned to the variable.
Table of Contents
Until Java 9, developers had to mention the type of the local variable explicitly and make sure that it is compatible with the value, it is initialized with.
See this simple line of code below:
var output_msg = "declaring a local variable in Java 9";
The data type of output_msg is not provided. Instead, it is marked as a var. Now the compiler will infer the type of output_msg from the type of the value assigned to it.
Here the data type of output_msg would be String.
The following two examples demonstrate the Java 9 approach that will be later used to explain the need for this feature:
1. import java.util.ArrayList; 2. import java.util.List; 3. class class01 { 4. public static void main(String a[]) 5. { 6. List<Map> myData = new ArrayList<>(); 7. } 8. } 9. 10. class class02 { 11. public static void main(String a[]) 12. { 13. String str = " Hello World"; 14. } 15. }
It works just fine, right? and this is how things have been since the beginning but there is one slight issue that had some room for improvement. When you create an object, it is very obvious that if the type of the object is mentioned at the right side of the expression, so mentioning the same thing before the name of the variable makes it redundant.
Along with this, you can observe it from the second example, you can see that it is very clear that after the ‘=’ sign, it is a string being enclosed in double inverted commas. Therefore, removing the datatype can eliminate the redundancy and make variable declaration shorter, and more convenient.
As mentioned in the very first example, it is quite simple. Instead of mentioning the variable datatype on the leftmost side, before the variable, you can use the keyword ‘var’. see this comparison below,
1. // Normal variable declaration 2. import java.util.ArrayList; 3. import java.util.List; 4. class class01 { 5. public static void main(String ap[]) 6. { 7. List<Map> data = new ArrayList<>(); 8. } 9. }
Can be written as:
1. // Java code for local variable 2. import java.util.ArrayList; 3. import java.util.List; 4. class class01 { 5. public static void main(String ap[]) 6. { 7. var data = new ArrayList<>(); 8. } 9. }
Following are the possible scenarios where it is permitted to use Java local interference:
1. class example01 { 2. static 3. { 4. var x = " Java local interference "; 5. System.out.println(x)' 6. } 9. public static void main(String[] ax) 10. { 11. } 12. }
The output will be:
Java local interference
1. class example02 { 2. public static void main(String a[]) 3. { 4. var x = " Java local interference "; 5. System.out.println(x) 6. } 7. }
1. // with an enhanced for-loop 2. 3. class example03a { 4. public static void main(String a[]) 5. { 6. int[] myArr = new int[5]; 7. arr = { 1, 2, 3, 4, 5}; 8. for (var i : myArr) 9. System.out.println(i + ", "); 10. } 11. } 12. 13. 14. // OR with a simple for-loop 15. class examplw03b { 16. public static void main(String a[]) 17. { 18. int[] myArr = new int[5]; 19. arr = { 1, 2, 3, 4, 5 }; 20. for (var i = 0; i < 5; i++) 21. System.out.println(myArr[i] + ", "); 22. } 23. }
1, 2, 3, 4, 5,
1. class example04 { 2. int func01() 3. { 4. var num = 100; 5. return num; 6. } 7. public static void main(String a[]) 8. { 9. var num = new example04().func01(); 10. System.out.println(“The return value is”, num); 11. }
The return value is 100
Following are the certain cases where the declaration of local variables using Java local interference will result in an error :
1. class example01 { 2. var x = 2; }
The error output on the screen:
Error: class variables can't be declared using 'var'. Datatype needs to be explicitly mentioned
1. class example 2 { 2. public static void main(String a[]) 3. { 4. var x; 5. } 6. }
Error: cannot use 'var' on variable without initializer
1. class example03 { 2. public var showResult(var num) 3. { 4. } 5. }
Error: can't use 'var' on method parameters Error: Method return type can't be var
If you attempt to use var with the anonymous class instance, it will output an unexpected result, for instance see this code demonstration:
1. public void VarInitWithAnonymous () { 2. var obj01 = new Object() { }; 3. assertFalse(obj01.getClass().equals(Object.class)); 4. }
Now, if you try to assign another Object to obj01, it will result in a compilation error. This is because the inferred type of obj isn’t Object.
Obj01 = new Object();
This will be the output:
Error: Object cannot be converted to <anonymous Object>
1. class example04 { 2. public static void main(String a[]) 3. { 4. var i = NULL; 5. }
Output:
Error: variable initializer is 'null'
It is to be noted that var is not a keyword. It is a reserved type name, just like float or int. This ensures backward compatibility for programs where you have used var may be as a function or to name a variable
There is also no runtime overhead in using var. and it surely does not make Java a dynamically typed language. The type of the variable is still inferred at compile time and cannot be changed later.
In this article, the new Java 10 local variable type inference is demonstrated with several examples. It is a good improvement over the previous declaration method to remove redundancy and make your code shorter. Although you need to follow the guidelines and prevent using any illegal method to apply var.
Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.
Create a free profile and find your next great opportunity.
Sign up and find a perfect match for your team.
Xperti vets skilled professionals with its unique talent-matching process.
Connect and engage with technology enthusiasts.
© Xperti.io All Rights Reserved
Privacy
Terms of use