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

- Vue.js 3.x快速入門
- Facebook Application Development with Graph API Cookbook
- 微信公眾平臺與小程序開發:從零搭建整套系統
- 樂高機器人設計技巧:EV3結構設計與編程指導
- Animate CC二維動畫設計與制作(微課版)
- 量化金融R語言高級教程
- Instant Ext.NET Application Development
- Quantum Computing and Blockchain in Business
- Learning Alfresco Web Scripts
- SaaS攻略:入門、實戰與進階
- H5頁面設計與制作(全彩慕課版·第2版)
- Python全棧開發:數據分析
- Web前端開發技術實踐指導教程
- Node.js Web Development
- Django 2.0 入門與實踐