- 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.
推薦閱讀
- WildFly:New Features
- 算法基礎:打開程序設計之門
- JavaScript 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- R語言數據可視化實戰
- INSTANT Weka How-to
- 單片機應用技術
- 重學Java設計模式
- Python:Master the Art of Design Patterns
- C# and .NET Core Test Driven Development
- 快速入門與進階:Creo 4·0全實例精講
- Python Machine Learning Blueprints:Intuitive data projects you can relate to
- 玩轉.NET Micro Framework移植:基于STM32F10x處理器
- 大學計算機應用基礎(Windows 7+Office 2010)(IC3)
- Moodle 3.x Developer's Guide
- 菜鳥成長之路