- Java 11 and 12:New Features
- Mala Gupta
- 153字
- 2021-07-02 12:26:59
Using var with arrays
Using var doesn't imply just dropping the type of the local variable; what remains should enable the compiler to infer its type. Imagine a method that defines an array of the char type, as follows:
char name[] = {'S','t','r','i','n','g'};
You can't replace the data type name, that is, char, in the preceding code with var and define it using any of the following code samples:
var name[] = {'S','t','r','i','n','g'}; var[] name = {'S','t','r','i','n','g'}; var name = {'S','t','r','i','n','g'};
Here's one of the ways to include relevant information, so that the compiler can infer the type:
var name = new char[]{'S','t','r','i','n','g'};
It seems like the Java compiler is already struggling with this assumption from the programmers, as shown in the following image:

You can't just drop the data types in order to use var. What remains should enable the compiler to infer the type of the value being assigned.
推薦閱讀
- Puppet 4 Essentials(Second Edition)
- TypeScript Blueprints
- Hands-On Image Processing with Python
- PyQt從入門到精通
- 趣學Python算法100例
- 深入理解Java7:核心技術與最佳實踐
- 假如C語言是我發明的:講給孩子聽的大師編程課
- 碼上行動:用ChatGPT學會Python編程
- Learning Hunk
- R Data Analysis Cookbook(Second Edition)
- C語言開發基礎教程(Dev-C++)(第2版)
- AutoCAD 2009實訓指導
- R語言:邁向大數據之路(加強版)
- ASP.NET 4.0 Web程序設計
- 進入IT企業必讀的324個Java面試題