Local-Variable Type Inference


Advanced Java Programming
PREVIEW11m 49s

The course is part of this learning path

Start course

This training course provides you with a deep dive into generics, type inference, Lambda expressions, and functional interface development.

Learning Objectives

What you'll learn:

  • What generics are and when and why you might choose to implement them
  • Type inference and the var keyword
  • The basic concept of functional programming
  • How to write basic Lambda expressions
  • Functional interfaces and when to use them
  • The key differences between anonymous classes and lambda expressions


Intended Audience

  • Software Engineers interested in advancing their Java skills
  • Software Architects interested in using advanced features of Java to design and build both applications and frameworks
  • Anyone interested in advanced Java application development and associated tooling
  • Anyone interested in understanding the advanced areas and features of the Java SDK

Okay, welcome back. In this lecture, we'll explore the concept of local-variable type inference. In particular, we'll review the following topics. We'll provide an explanation of type inference. Then we'll introduce the local-variable type inference as introduced in Java 10. And introduce the var reserved type name. At the conclusion of this lecture, you should be able to perform each of the items listed above. Take a moment to rate yourself on each of these items on a scale of one through to five. At the conclusion of this lecture, these objectives will be reviewed. You should rate yourself again to see how much benefit you have received from this lecture. Type inference is the automatic detection of a data type, instead of explicitly defining a variable type. Java always required an explicit type to be defined when referencing an object, often resulting in a duplicate definition of the type, once for the definition of the variable type and once when invoking the constructor of the object of which the reference must be assigned to the variable. Java 10 enhances the type inference of the compiler, which was introduced in Java 7, for local variable types. When declaring a local variable, the type of the variable no longer has to be defined explicitly. Instead, the type can be defined using the var type parameter. For more than 20 years, the Java programming language required that variable types were explicitly declared, while other programming languages have supported this type of type inference for several years. Java developers had to wait until the release of Java 10 before this feature could be used. The var type can only be used to define local variables and not to define instance variables. In order for the compiler to be able to infer the type of the variable, a variable of type var must be declared and initialized at the same time. The var type cannot be used when defining compound declarations. The var type can be used within a method to define a local variable. The variable can be returned from the method as long as the inferred type of the variable matched the return type of the method. It can even be used to reference the result of a method invocation. Even though this is a possibility, the resulting code might become hard to understand since it becomes hard to figure out what the actual type of the variable is. The var type can also be used when defining a for-loop, both in the enhanced for-loop or as the type defining the looping index in a traditional for-loop. The var type can also be used to reference an array type, either declared explicitly or obtained from a method invocation. It is not possible to declare an array of var types. By using local-variable type inference, developers no longer need to define the type of a local variable. In other words, it focuses on the left-hand side of the declaration. In earlier versions of Java, starting with Java 7, type inference focused on the right-hand side of the declaration, removing the need for a duplicate type declaration when using generics. With the introduction of Java 10, this causes a bit of a problem. When declaring a variable using the var type on the left-hand side of the declaration and also using the diamond operator when instantiating the object on the right-hand side, the result is a reference that uses a generic type of type object. To overcome this problem, the generic type should now, once again, be defined on the right-hand side of the declaration. As mentioned before, the var type can only be used to declare local variable types, so they cannot be used to define instance variables or within method signatures. Adding new keywords to a programming language often causes problems with existing code, as the keyword might already have been used in existing code to define classes, methods, or variables. In Java 10, var has not been defined as a keyword. Instead, it has been defined as a reserved type name, so it can still be used to define methods, variables, parameters, and methods. It can no longer be used as a class name. When trying to compile legacy code that contains a class called var, it will result in a compilation error. But, since most developers follow the Java naming convention when it comes to the naming of classes, for example, class names should always start with an uppercase, this problem should not occur. Now, the reason for introducing local-type inference has never been to limit or reduce the amount of code that has to be written, but more to improve the readability of code. As many software architects have stated, code is read more often than it is written. Code that we write should always be easy to read and maintain. The more readable code is, the easier it is to manage, update, and debug, in the case it was written by someone else. By removing the duplication of code, code can become easier to read. By removing all boilerplate code, we are left with the code that performs the required logic. As shown by the code examples above, in earlier versions of Java, the type of each variable had to be declared explicitly. By replacing all of these explicit types by the var type, old variable names are now properly aligned, making the code more readable. Keep in mind that improving readability of code also includes the proper naming of method and variable names. This becomes even more important when the explicit type is removed from the declaration. The variable should now be completely self-explanatory, to clearly reveal its intent. When improperly used, the var type can also make your code less readable. In the example shown above, the type of the employee data variable can no longer be determined by just reading the code. When your code becomes less readable because you are using the var type, you should consider using explicit types instead. Keep in mind that types are inferred at compile time. The generated bytecode does include information about the type being used. Using the var type should not affect the runtime performance of your application. IDEs will typically assist in the use of the var type. When using code completion, they will only show the var type as an option when it is valid to use. When the IDE is used to obtain information about a variable, it will show the JavaDoc for the inferred type and the methods that can be invoked on an object of that type. Eclipse even added a quick assist option to the IDE which allows the var type to be changed into the inferred type. Naturally, the IDE must provide support for Java 10 in order to be able to provide this kind of developer assistance. Okay, before we complete this lecture, pause this video and consider the following questions to test yourself on the content that we have just reviewed. Write down your answers for each question and then resume the video to compare answers. Okay, the answers to the above questions are, one, for local variable declarations, enhanced for-loop indexes, and index variables declared in traditional for-loops. Two, improve the readability of Java code and avoid code duplication.

About the Author
Learning Paths

Jeremy is a Content Lead Architect and DevOps SME here at Cloud Academy where he specializes in developing DevOps technical training documentation.

He has a strong background in software engineering, and has been coding with various languages, frameworks, and systems for the past 25+ years. In recent times, Jeremy has been focused on DevOps, Cloud (AWS, Azure, GCP), Security, Kubernetes, and Machine Learning.

Jeremy holds professional certifications for AWS, Azure, GCP, Terraform, Kubernetes (CKA, CKAD, CKS).

Covered Topics