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

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.
主站蜘蛛池模板: 东港市| 延庆县| 颍上县| 调兵山市| 沙雅县| 伊金霍洛旗| 金坛市| 独山县| 黑龙江省| 旬阳县| 城口县| 乌兰察布市| 加查县| 黄大仙区| 大同市| 长春市| 长岭县| 江山市| 星子县| 万年县| 虞城县| 海丰县| 京山县| 乐平市| 五大连池市| 泾源县| 普安县| 凤凰县| 绥宁县| 大余县| 民和| 大城县| 宜良县| 木兰县| 仪陇县| 鸡东县| 荔浦县| 贵溪市| 西宁市| 兰溪市| 临西县|