How to Use the var Keyword for Local Variable Type Inference in Java 10

In Java 10, the var keyword was introduced to allow local variable type inference. This means that when you declare a local variable, the compiler automatically infers its type based on the initialization value. This improves readability and reduces boilerplate code, especially when working with complex types, without compromising type safety.

Here’s a guide on how to use the var keyword:


1. Declaring and Initializing Local Variables with var

The var keyword replaces explicitly specifying the type while declaring local variables. However, you must initialize the variable at the time of declaration, as the compiler needs an expression to infer the type.

// Example of using var keyword
var message = "Hello, Java 10!";  // Inferred as String
var number = 10;                 // Inferred as int
var list = List.of("apple", "banana", "orange"); // Inferred as List<String>

Here, the type of each variable is deduced by the Java compiler:

  • message: String
  • number: int
  • list: List<String>

2. Scopes Where var Can Be Used

The var keyword can only be used in specific contexts:

a. Local Variables in Methods

public void demoVarUsage() {
    var name = "John";      // Inferred as a String
    var age = 30;           // Inferred as an int

    System.out.println(name + " is " + age + " years old.");
}

b. Loop Variables (for-each or traditional for-loops)

// for each loop
var items = List.of("A", "B", "C");
for (var item : items) {
    System.out.println(item);  // item inferred as String
}

// traditional for loop
for (var i = 0; i < 10; i++) {
    System.out.println(i);     // i inferred as int
}

c. Local Variables in Lambda Expressions

var lambda = (String x, String y) -> x + y; // Explicit lambda types
System.out.println(lambda.apply("Java", "10"));

3. Restrictions on var Usage

While var is versatile, there are limitations:

  1. Cannot Be Used Without Initialization
    var name; // Compilation error: cannot infer type
    name = "John";
    
  2. Cannot Be Used with Null Initializer
    var something = null; // Compilation error
    
  3. Cannot Be Used as a Method Parameter, Field, or Return Type
    The var keyword is limited to local variables inside methods and blocks, as well as loop variables. It cannot be used:

    • As a return type of method.
    • As a field in a class.
    • As a method parameter.
    public var getName() {    // Compilation error: 'var' is not allowed here
       return "Java";
    }
    
  4. Cannot Mix Explicit Types and var
    var name = "John", age = 30; // Compilation error
    var name = "John";
    var age = 30;               // Declare separately
    
  5. Cannot Infer Ambiguous Types
    var result = process();  // If `process()` returns Object, type can't be narrowed.
    

4. Advantages of Using var

  • Improved Code Readability: Reduces verbosity for complex types.
    var map = new HashMap<String, List<Integer>>(); // Cleaner than HashMap<String, List<Integer>>
    
  • Consistent with Type Inference: Makes Java more modern and closer to languages like Kotlin, Scala, or C#.


5. Best Practices

  • Avoid overusing var to ensure code remains understandable.
  • Use meaningful names for variables to compensate for the lack of explicit type.
  • Use var only when the type is obvious from the context.

Example Code:

package org.kodejava.basic;

import java.util.List;

public class VarExample {
   public static void main(String[] args) {
      // Using var for various local variable declarations
      var name = "Alice";                        // String
      var age = 25;                              // int
      var fruits = List.of("Apple", "Banana");  // List<String>

      System.out.println(name + " likes " + fruits);

      for (var fruit : fruits) {
         System.out.println(fruit);  // Inferred as String
      }

      var sum = add(10, 20);  // Inferred as int
      System.out.println("Sum: " + sum);
   }

   private static int add(int a, int b) {
      return a + b;
   }
}

Output:

Alice likes [Apple, Banana]
Apple
Banana
Sum: 30

The var keyword is a helpful addition, especially for simplifying local variables with inferred types, keeping code concise and readable while retaining type safety!

How do I use try-with-resources statement?

The try-with-resources statement is introduced in the Java 7. With this new statement we can simplify resource management in our program, also known as ARM (Automatic Resource Management).

This statement is a try statement that declares one or more resources. After the program finish with the resource, it must be closed. The try-with-resources ensures that each resource is closed and the end of the statement.

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

package org.kodejava.basic;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class TryWithResourceExample {
    public static void main(String[] args) {
        try {
            TryWithResourceExample demo = new TryWithResourceExample();
            demo.printStream("F:/tmp/data.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void printStream(String fileName) throws IOException {
        char[] buffer = new char[1024];

        try (InputStream is = new FileInputStream(fileName);
             Reader reader = new BufferedReader(
                     new InputStreamReader(is, StandardCharsets.UTF_8))) {

            while (reader.read(buffer) != -1) {
                System.out.println(buffer);
            }
        }
    }
}

How do I use the instanceof keyword?

To check whether an object is of a particular type (class or interface type) you can use instanceof operator. The instanceof operator is used only for object reference variable. x instanceof y can be read as x is-a y.

The instanceof returns true if the reference variable being tested is of the type being compared to. It will still return true if the object being compared is assignment compatible with the type on the right.

For interface type, an object is said to be of a particular interface type (meaning it will pass the instanceof test) if any of the object’s superclasses implement the interface.

package org.kodejava.basic;

interface Man {
}

public class InstanceofDemo {
    public static void main(String[] args) {
        Body body = new Body();
        Hand hand = new Hand();
        Nail nail = new Nail();
        Shoes shoe = new Shoes();

        if (body instanceof Man) {
            System.out.println("body is a Man");
        }

        if (hand instanceof Man) {
            System.out.println("hand is a Man too");
        }

        if (hand instanceof Body) {
            System.out.println("hand is a Body");
        }

        // it should be return false
        if (hand instanceof Nail) {
            System.out.println("hand is a Nail");
        } else {
            System.out.println("hand is not a Nail");
        }

        if (nail instanceof Man) {
            System.out.println("nail is a Man too");
        }

        if (nail instanceof Hand) {
            System.out.println("nail is a Hand");
        }
        if (nail instanceof Body) {
            System.out.println("nail is a Body too");
        }

        // it should return false, cause Shoes is not implements Man
        if (shoe instanceof Man) {
            System.out.println("shoe is a Man");
        } else {
            System.out.println("shoe is not a Man");
        }

        // compile error. cannot test against class in different
        // class hierarchies.
        //
        //if (shoe instanceof Body) {
        //}

    }

}

class Body implements Man {
}

// indirect implements Man
class Hand extends Body {
}

// indirect implements Man
class Nail extends Hand {
}

class Shoes {
}

The result of the code snippet above:

body is a Man
hand is a Man too
hand is a Body
hand is not a Nail
nail is a Man too
nail is a Hand
nail is a Body too
shoe is not a Man

How do I use the “this” keyword in Java?

Every instance method has a variable with the name this that refers to the current object for which the method is being called. You can refer to any member of the current object from within an instance method or a constructor by using this keyword.

Each time an instance method is called, the this variable is set to reference the particular class object to which it is being applied. The code in the method will then relate to the specific members of the object referred to by this keyword.

package org.kodejava.basic;

public class RemoteControl {
    private String channelName;
    private int channelNum;
    private int minVolume;
    private int maxVolume;

    RemoteControl() {
    }

    RemoteControl(String channelName, int channelNum) {
        // use "this" keyword to call another constructor in the 
        // same class
        this(channelName, channelNum, 0, 0);
    }

    RemoteControl(String channelName, int channelNum, int minVol, int maxVol) {
        this.channelName = channelName;
        this.channelNum = channelNum;
        this.minVolume = minVol;
        this.maxVolume = maxVol;
    }

    public static void main(String[] args) {
        RemoteControl remote = new RemoteControl("ATV", 10);

        // when the following line is executed, the variable in
        // changeVolume() is referring to remote object.
        remote.changeVolume(0, 25);
    }

    public void changeVolume(int x, int y) {
        this.minVolume = x;
        this.maxVolume = y;
    }
}

How do I use the “return” keyword in Java?

The return keyword is used to return from a method when its execution is complete. When a return statement is reached in a method, the program returns to the code that invoked it.

A method can return a value or reference type or does not return a value. If a method does not return a value, the method must be declared void and it doesn’t need to contain a return statement.

If a method declare to return a value, then it must use the return statement within the body of method. The data type of the return value must match the method’s declared return type.

package org.kodejava.basic;

public class ReturnDemo {

    public static void main(String[] args) {
        int z = ReturnDemo.calculate(2, 3);
        System.out.println("z = " + z);

        Dog dog = new Dog("Spaniel", "Doggie");
        System.out.println(dog.getDog());
    }

    public static int calculate(int x, int y) {
        // return an int type value
        return x + y;
    }

    public void print() {
        System.out.println("void method");

        // it does not need to contain a return statement, but it
        // may do so
        return;
    }

    public String getString() {
        return "return String type value";

        // try to execute a statement after return a value will
        // cause a compile-time error.
        //
        // String error = "error";
    }
}

class Dog {
    private String breed;
    private String name;

    Dog(String breed, String name) {
        this.breed = breed;
        this.name = name;
    }

    public Dog getDog() {
        // return Dog type
        return this;
    }

    public String toString() {
        return "breed: " + breed.concat("name: " + name);
    }
}

Sometimes learning Java can be challenging, but the main thing is to remember that you can find any help on our website. Just be dedicated and passionate about what you do. If you are still at university, a pay for essay service EssayWritingService can be of any assistance for you.