Saturday, 28 May 2016

Scope of Java Variables

Variable life span depends on its scope. Only 4 scopes:

1) Class variable //1 once class loaded, accessible by all instances of class
2) Instance variable //2 once instance constructed as calling its constructor.
3) Method argument variable //3 once method is invoked
4) Local variable //4 being alive within the method alone, or a block.

//1 outside all instances of the class; accessible by all instances method and class methods.
//2 outside all instance methods, can be accessible by them alone.
//3 method argument variable has a method scope.
//4 within in a scope of method, or a block, for example a if(){ }
The scope of a local variable depends its declaration place within the method

Please note:  instance variable cannot be accessible in a static context, i.e. by a class method.

/**
 *
 * @author YNZ
 */
public class BlockScope {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        boolean b = false; //method scope
        if (b) {
            int i = 0; //block scope
        } else {
            int i = 1; //block scope
        }

    }

}

Some rules:
(1) Class and instance var. should not be declared as the same name;(compiling error).
(2) Local var. and method parameter should not have the same name.(compiling error)
(3) Local var. can hide instance var and class var.
(4) Local var. must init. before using it, otherwise a compiling error.



/**
 *
 * @author YNZ
 */
public class LocalVar {

    static int i; //class var.

    public static void main(String[] args) {
        //int i=0; local var. must be init. before using it. 

        //local var. hiding the class field i.
        //Well, this is a java feature. this is not an error. 
        for (int i = 0; i < 10; i++) { //local var. i within scope of for loop.
            System.out.print(" " + Math.random());
        }

        System.out.println("");
        for (int i = 0; i < 10; i++) {//local var. i with scope of for loop.
            System.out.print(" " + Math.random());
        }

        System.out.print("\n");
    }

    public void m() {
        int d; //method variable(local var.) 
        //d++, it must be init. before using it; otherwise it gives comipling error. 
        {
            {
            }
        };
    }

    public void m(int x) {
        int y = 0;  //int x =0 will cause an error
        if (true) {
            int z = 0;  //life span within if block
        } else {
            int z = 100; //life span within else block
        }
        int z =300;  //so here it is valid. 
        System.out.println(z); 

    }
}



No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...