Inferring declarations with the var identifier

We can use the new var identifier, as with the following example, to infer our data type. So, instead of explicitly declaring data types, we can infer them:

var myList = new ArrayList<String>();

The preceding code infers ArrayList<String>, so we no longer need to use the verbose ArrayList<String> myList = new ArrayList<String>(); syntax.

The introduction of the var identifier should not be construed as adding a new keyword to the Java language. The var identifier is technically a reserved type name. 

There are a few restrictions to using the new identifier. For example, they cannot be used when any of the following conditions exist:

  • No initializer is used
  • Multiple variables are being declared
  • Array dimension brackets are used
  • A reference to the initialized variable is used

As expected, javac will issue specific error messages if var is used incorrectly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset