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.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.27.178