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

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.
主站蜘蛛池模板: 恭城| 普安县| 平定县| 高邑县| 舒城县| 鄢陵县| 大英县| 金秀| 老河口市| 宁安市| 藁城市| 台北县| 蒲城县| 杭锦后旗| 左权县| 卢龙县| 郧西县| 北票市| 洛扎县| 苍梧县| 嘉善县| 蒙山县| 西盟| 广汉市| 淮安市| 邻水| 苍南县| 泸定县| 长顺县| 历史| 太康县| 衡山县| 土默特左旗| 开化县| 安新县| 乌拉特前旗| 漳州市| 上林县| 永寿县| 溆浦县| 越西县|