Can static variables be local?

|
| By Webner

Static variables are the variables that belongs to class. Static variables are shared among all the objects i.e there is only single copy of that variable.These do not get memory in each object. They automatically get initialised to 0.

For Example :

class Example {
    static int count;
    int instance_var;
    Example() {
    count++;
    }
    Example(int instance_var) {
    count++;
    this.instance_var = instance_var;
    }
    public static void noOfObjects() {
    System.out.println(“No of objects: ”+count);
    }
}
class Main {
    public static void main(String s[]) {
    Example example_obj1 = new Example();
    Example example_obj2 = new Example(23);
    Example.noOfObjects();
    }}

Output: No of objects: 2

In this example, the variable count is static that is shared between objects example_obj1 and example_obj2 and it is used to count the number of objects.

Local variables are the variables that are declared within a method or a block. Their scope is within that method or block in which they are declared.

For Example:

In the example above of Example class, instance_var when used in a constructor:

Example(int instance_var) {
    count++;
    this.instance_var = instance_var;
}

is a local variable and it only exists within this constructor.

No, Local variables cannot be static because local variables get memory in a stack but static variables get memory in heap.

Local variables get destroyed on returning from the method or block in which those were declared but static variables remain in the class area till the class is loaded and we are working on that class.

For Example:

class Example {
    public static void exampleMethod(int local_variable) {
    System.out.println(“local_variable = ”+local_variable);
    }
    public static void main(String[] args) {
    System.out.println(“local_variable = ”+local_variable);
    }
}

This will generate a compile time error in the main method that local_variable is not defined because it is a local variable and its scope is the exampleMethod method only.

But if we declare it as static :

public static void exampleMethod(static int local_variable) {
System.out.println(“local_variable = ”+local_variable);
}

This means we are storing this variable in class area and it can be accessed by the class name. But practically it is not possible because local variables do not exist outside that method or block and also get stored in the stack, not in the class area.Therefore, it will generate an error that local variables cannot be static.

Leave a Reply

Your email address will not be published. Required fields are marked *