官术网_书友最值得收藏!

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:

This chapter includes a couple of code-check exercises for you to try. The exercises use the names of two hypothetical programmers—Pavni and Aarav.
主站蜘蛛池模板: 睢宁县| 武平县| 连平县| 平陆县| 平谷区| 鄂伦春自治旗| 昭平县| 万山特区| 涿鹿县| 宜黄县| 台前县| 诸暨市| 获嘉县| 高唐县| 乐昌市| 泰宁县| 石嘴山市| 兴仁县| 临海市| 黄骅市| 九龙坡区| 龙口市| 出国| 呈贡县| 花莲县| 三明市| 威远县| 和顺县| 晋江市| 平邑县| 昌都县| 镶黄旗| 云霄县| 黄平县| 和田市| 体育| 旌德县| 葫芦岛市| 开化县| 寿宁县| 香河县|