- 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.
推薦閱讀
- Learning PostgreSQL
- Maven Build Customization
- C語言程序設計
- Go并發編程實戰
- Hands-On GUI Programming with C++ and Qt5
- Java 從入門到項目實踐(超值版)
- Training Systems Using Python Statistical Modeling
- Julia數據科學應用
- Python預測分析與機器學習
- C語言程序設計與應用實驗指導書(第2版)
- Hands-On Dependency Injection in Go
- 每個人的Python:數學、算法和游戲編程訓練營
- Java EE基礎實用教程
- Learning GraphQL and Relay
- TensorFlow 2.0深度學習應用實踐