Java var Keyword Simplifies Variable Declarations

Since Java 10, Java introduced a handy feature called var that allows the compiler to infer the type of local variables from their initializer, making code easier to read. // Without var String name = "Java"; URL url = new URL("http://google.com"); // With var var name = "Java"; var url = new URL("http://google.com"); Here are the best way to use it: Use var when: • The type is obvious from the constructor:   var list = new ArrayList<String>(); (No need to write ArrayList<String>() twice) • Handling complex generics: Prefer: var map = new HashMap<String, List<Order>>(); than: Map<String, List<Order>> map = new HashMap<String, List<Order>>(); • The variable name provides enough context: var customer = service.findCustomerById(id); (The name customer tells what it is) Avoid var when: • The initializer is not obvious: var result = o.calculate(); (Hard to tell if result is an int, a double or a Result object...) • The variable has a long scope: if a method is 50 lines long, using var at the top makes it harder to remember the type when reaching the bottom. • Using var in method signatures (not allowed anyway): Java only allows var for local variables, not fields, parameters, or return types.

To view or add a comment, sign in

Explore content categories