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

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.
主站蜘蛛池模板: 济南市| 余干县| 霍州市| 乐山市| 基隆市| 威信县| 天柱县| 洱源县| 凤凰县| 阜宁县| 金塔县| 昭通市| 舞阳县| 伊金霍洛旗| 太康县| 大连市| 龙陵县| 松滋市| 望都县| 双桥区| 东台市| 来宾市| 乐东| 乳山市| 城步| 和林格尔县| 平凉市| 邹平县| 楚雄市| 二手房| 高青县| 广宁县| 海晏县| 民权县| 五指山市| 开鲁县| 黑山县| 内乡县| 德安县| 中方县| 伊金霍洛旗|