Java variable scope (range where variables can be seen)

Introduction

This article is a record of what I understand for those who are studying Java.

In my article, the main Java features are summarized in the list below. This time, it is assumed that you have some understanding of variables and types, so if you have any questions, please check from the link below.

-Variables and types, type conversion -Variable scope Current page ・ Character string operation (in preparation) ・ Array operation (in preparation) ・ Operator (in preparation) ・ Conditional branch (in preparation) ・ Repeat processing (in preparation) -Exception handling ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation)

Variable scope

About Java variable declaration, initialization, and type The link above is my article I mentioned earlier, but there are other things to keep in mind when declaring and referencing variables. That is the range in which you can see the variables. In the following, local variables and static variables are used as examples.

class Main{
    public static void main(String args[]){
        int i = 30;
        
        System.out.println(i);
    }
}

Declaring an int i in the main method. So you can use it in main until the main process is finished. When you run

30

Is displayed, so the contents of i can be displayed. If you just limit the place to declare, you may not be able to find the variable.

class Main{
    public static void main(String args[]){
        if(true){
            int i = 30; //Declared in if
        }
        
        System.out.println(i);
    }
}

If you execute this description, you will get the following error.

error:Can't find symbol
        System.out.println(i);
                           ^

I can't find i because I declare it in if. I think that such mistakes will disappear if we declare it in a wide range so that this does not happen, but this method has pitfalls.

class Main{
    static int i = 30;
    public static void main(String args[]){
        System.out.println(i);
        plus20();
    }

    static void plus20(){
        i = i + 20;
        System.out.println(i);
    }
}

When you do the above,

30
50

Will be. Since i is declared to be usable anywhere in the class, you can get the inside of the variable with both plus20 and main. This description seems to be fine, but for example, the plus20 method is a method that just wants to display the state of adding 20, and when you want to display the original value later, the value of i is rewritten with plus20. I will end up.

class Main{
    static int i = 30;
    public static void main(String args[]){
        System.out.println(i);
        plus20();
        System.out.println(i);
    }

    static void plus20(){
        i = i + 20;
        System.out.println(i);
    }
}

When you run

30
50
50

In the order of the code, I would like the third number to be 30, but since the value has been rewritten in plus20, it is 50. Since such troubles occur, I think it is better to narrow down the range of variables as much as possible.

class Main{
    public static void main(String args[]){
        int i = 30;
        System.out.println(i);
        plus20(i);
        System.out.println(i);
    }

    static void plus20(int z){
        z = z + 20;
        System.out.println(z);
    }
}

When you run

30
50
30

Even if I added the values in plus20, it did not interfere with i, so I was able to get the original value of i.

Each has a name depending on the reference range of the variables mentioned above.

Local variables

Basically, variables used inside a method are local variables that cannot be referenced outside the method.

class Main{
    public static void main(String args[]){
        int i = 100; //from here


        System.out.println(i);
        //So far
    }
}

Basically, I want to narrow the reference range of variables, so I think it is easy to describe this.

Instance variables

Basically, write the declaration under the class and handle it within the class

class Mikan{
    int i;

    Mikan(){
        this.i = 10;
    }
}

It is declared for each instance when Mikan is instantiated. If you make two Mikans, it feels like each has an int i. In the case of this definition, it is a variable that can be used inside the instance, and you can also create an instance externally and read the variable.

class Mikan{
    int j;
    Mikan(){
        this.j = 10;
    }

}

class Main{
    public static void main(String args[]){
        Mikan mikan1 = new Mikan();
        Mikan mikan2 = new Mikan();

        mikan2.j += 10;

        //Instance variables
        System.out.println(mikan1.j);
        System.out.println(mikan2.j);
    }
}

If you run it here

10
20

It will be displayed. You can create a Mikan instance in the Main class and refer to the variables in it.

static variable (class variable)

Static variables are similar to the instance variables above, but you can use them without instantiating them.

class Mikan{
    static int i = 10;

}

class Main{
    public static void main(String args[]){
        System.out.println(Mikan.i);
    }
}
10

It looks like an instance variable, but it has a variable each time it is created. Static variables share the same value within the class.

class Mikan{
    static int i = 10;
    int j;
    Mikan(){
        this.j = 10;
    }

}

class Main{
    public static void main(String args[]){
        Mikan mikan1 = new Mikan();
        Mikan mikan2 = new Mikan();

        mikan2.j += 10;

        //Instance variables
        System.out.println(mikan1.j);
        System.out.println(mikan2.j);

        //static variable
        
        System.out.println(Mikan.i);

        Mikan.i += 30;

        System.out.println(Mikan.i);
    }
}
10
20
10
40

If you want to have a unique value for each instance, use an instance variable, and if you want to see one variable in common, use a static variable.

Also, when calling an instance variable or static variable from a function in the class, it will be described like this.

class Mikan{
    static int i = 10;
    int j = 50;

    void inscheck(){
        //static variables can be called
        System.out.println(i);

        //Instance variables can be called
        System.out.println(j);
    }

    static void check(){
        //static variables can be called
        System.out.println(i);

        //Instance variables cannot be called
        // System.out.println(j);
    }
}

class Main{
    public static void main(String args[]){
        Mikan mikan1 = new Mikan();

        //Functions that the instance has
        mikan1.inscheck();

        //static function
        Mikan.check();
    }
}

When you run

10
50
10

It will be. Both can be called from the function of the instance called from the instance.

In the case of a static function called from a class, static variables can be called, but instance variables cannot be called.

If you uncomment and compile

test.java:18:error:Non-static variable j cannot be referenced from static context
        System.out.println(j);
                           ^
1 error

I will come out. If you get an error like this, you can solve it quickly by checking the qualifier of the variable specification.

At the end

It was an explanation about the range where variables can be seen. If you understand this area better, you will have fewer bugs such as unintended values.

Recommended Posts

Java variable scope (range where variables can be seen)
Range where variables can be used with ruby [Scope]
About the range and scope where Day16 variables can be used
Java variable scope (scope)
Java variable scope
[Introduction to Java] Variable scope (scope, local variables, instance variables, static variables)
[Basic knowledge of Java] Scope of variables
Java and Swift comparison (1) Source control / Scope / Variables
[Java] char type can be cast to int type