- Java 11 and 12:New Features
- Mala Gupta
- 288字
- 2021-07-02 12:26:58
Local variables
The usage of var is limited to local variables. These variables are used to store intermediate values and have the shortest life span, as compared to the instance and static variables. The local variables are defined within a method, constructor, or initializer block (both instance and static). Within a method or initializer, they can be defined within constructs, such as if..else loops, switch statements, and the try-with-resources construct.
The following is an example of Person class, showing possible usage of var to define local variables in initializer blocks, methods (including constructors), loops, as a local variable within switch branches, or a try with resources statement:
public class Person { { var name = "Aqua Blue"; // instance initializer block } static { var anotherLocalVar = 19876; // static initializer block } Person() { var ctr = 10; // constructor for (var loopCtr = 0; loopCtr < 10; ++loopCtr) { // loop -
// for switch(loopCtr) { case 7 :{ var probability = ctr / loopCtr; // switch System.out.println(probability); break; } } } } public String readFile() throws IOException { var filePath = "data.txt";
// try with resources
try (var reader = new BufferedReader(new FileReader(filePath))) { return reader.readLine(); } } }
As you can notice from the preceding code, a local variable can be declared using var at varied places in a class. Do you remember most of them? If not, let's make it simple for you.
Let's use an application to find all possible places where you could define local variables using var and mark it pictorially:

- NLTK基礎(chǔ)教程:用NLTK和Python庫構(gòu)建機器學習應(yīng)用
- 數(shù)據(jù)結(jié)構(gòu)簡明教程(第2版)微課版
- 人臉識別原理及算法:動態(tài)人臉識別系統(tǒng)研究
- Python數(shù)據(jù)分析(第2版)
- 網(wǎng)店設(shè)計看這本就夠了
- TradeStation交易應(yīng)用實踐:量化方法構(gòu)建贏家策略(原書第2版)
- C語言程序設(shè)計教程
- SQL Server數(shù)據(jù)庫管理與開發(fā)兵書
- 利用Python進行數(shù)據(jù)分析
- RealSenseTM互動開發(fā)實戰(zhàn)
- Android嵌入式系統(tǒng)程序開發(fā):基于Cortex-A8(第2版)
- PHP與MySQL權(quán)威指南
- Web程序設(shè)計:ASP.NET(第2版)
- Node.js區(qū)塊鏈開發(fā)
- 創(chuàng)意UI Photoshop玩轉(zhuǎn)移動UI設(shè)計