What is it?
- New way of declaring local variable – ‘var’
- Variable with ‘var’ type can be declared. Using this, the type of the variable is inferred from the context
- Only allowed for method local variables
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package ravi.tutorial.java.java10; /* * Demo for var type in Java 10 */ public class VarTypeDemo { public static void main(String[] args) { var name = "Name"; printVariableInfo(name); var number = 10; printVariableInfo(number); var numberLong = 10L; printVariableInfo(numberLong); var employee = new Employee(); printVariableInfo(employee); } private static void printVariableInfo(Object obj) { System.out.println("[CLASS]: " + obj.getClass() + " [VALUE]: " + obj); } } class Employee { @Override public String toString() { return "This is Employee !"; } } |
Output:
1 2 3 4 |
[CLASS]: class java.lang.String [VALUE]: Name [CLASS]: class java.lang.Integer [VALUE]: 10 [CLASS]: class java.lang.Long [VALUE]: 10 [CLASS]: class ravi.tutorial.java.java10.Employee [VALUE]: This is Employee ! |
References:
https://docs.oracle.com/javase/10/language/toc.htm#JSLAN-GUID-7D5FDD65-ACE4-4B3C-80F4-CC01CBD211A4