- 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:

- Java語言程序設計
- C++案例趣學
- 深入理解Android(卷I)
- iOS面試一戰到底
- Visual FoxPro程序設計教程(第3版)
- 深入淺出Electron:原理、工程與實踐
- 小創客玩轉圖形化編程
- Machine Learning with R Cookbook(Second Edition)
- Raspberry Pi for Secret Agents(Third Edition)
- UML+OOPC嵌入式C語言開發精講
- MySQL數據庫基礎實例教程(微課版)
- Learning ArcGIS for Desktop
- C語言程序設計實驗指導 (第2版)
- Creating Mobile Apps with jQuery Mobile(Second Edition)
- 單片機原理及應用技術