Example of using var keyword in java

March 23, 2020 | No comments

uses of var in java

Java 10 onwards introduced a new feature called local variable type inference The main advantage of this feature is to reduce boilerplate variable type definitions and to increase code readability.

The var keyword allows local variable type inference, which means the type for the local variable will be inferred by the compiler, so you don’t need to declare that. Hence, we can write code as bellow. Notice the variable type is var and its type will be assigned by compiler.
var map = new HashMap<String, List<Integer>> ();
var topResult = new ArrayList<String>();
var targetId = "UserID12345"; //infer String

Examples of using var

Working with var in a loop
var users = new ArrayList();
for (var user : users) {
Working with List
var list = Arrays.asList("UserOne", "UserTwo", "UserThree", "UserFour", "UserFive");
var firstUser = list.get(0);
Working with method which returns a complex data structure. In the following example rather then repeating the HashMap> every time, we can use a var type variable and work with that. Both inside the method and while calling the method.
public HashMap> getStudentCourses () {
  var studentCourses = new HashMap> ();
  return studentCourses;
//calling the method
var studentCourses = getStudentCourses();
Where var cannot be used
  • var cannot be used without an initializer.
  • var cannot be assigned null, since then the compiler cant figure out it's type.
  • once a var is initialized, we cannot assign a different data type value to it.
  • polymorphic assignments does not work with var variables.
  • var cannot be used in method arguments.
  • var cannot be used with compound declarations.

No comments :

Post a Comment

Please leave your message queries or suggetions.