- Java 11 and 12:New Features
- Mala Gupta
- 297字
- 2021-07-02 12:26:58
Type inference with var
The following lines of code show how local variables (and all other variables) were defined prior to Java 10:
String name = "Java Everywhere"; LocalDateTime dateTime = new LocalDateTime.now();
Starting with Java 10, by using var, you can drop the mandatory explicit type in the declaration of local variables, as follows:
var name = "Java Everywhere"; // variable 'name' inferred as
// String var dateTime = new LocalDateTime.now(); // var 'dateTime' inferred as
// LocalDateTime
Does it look like the preceding code doesn't offer a lot of benefits? Imagine you could take the following code:
HashMap<Integer, String> map = new HashMap<Integer, String>();
And replace it with this code, instead:
var map = new HashMap<Integer, String>();
By replacing HashMap<Integer, String> with var, the preceding line of code is much shorter.
When you move away from explicitly stating the data type of the variables, the compiler takes over to determine, or infer, the variable type. Type inference is the compiler's ability to evaluate the information that is already present in the code, like the literal values, operations, and method invocations or their declarations, to determine the variable type. It follows a set of rules to infer the variable type. As a developer, when you choose type inference with var, you should be aware of the compiler's inference algorithm, so that you don't get unexpected results.
With every new feature, you should adhere to a few rules and restrictions and try to follow the best practices to benefit from that feature. Let's start with the compulsory initialization of the variables that are defined using var.
- 多媒體CAI課件設計與制作導論(第二版)
- 手機安全和可信應用開發指南:TrustZone與OP-TEE技術詳解
- LaTeX Cookbook
- Java Web開發學習手冊
- CMDB分步構建指南
- 深入淺出Java虛擬機:JVM原理與實戰
- Practical Data Science Cookbook(Second Edition)
- 從Excel到Python:用Python輕松處理Excel數據(第2版)
- Visual Basic程序設計上機實驗教程
- Python機器學習:預測分析核心算法
- Regression Analysis with Python
- INSTANT Silverlight 5 Animation
- Unity 2018 Augmented Reality Projects
- Visual Basic程序設計實驗指導及考試指南
- JavaEE架構與程序設計