+1 vote
in JAVA by
Why are Static variables used in Java?

1 Answer

0 votes
by
Why are Static variables used in Java?

Static methods and variables are used in java to maintain a single copy of the entity across all objects. When a variable is declared as static it is shared by all instances of the class. Changes made by an instance to the variable reflect across all instances.

public class static_variable {

    static int a;

    static int b;

    static_variable(){

        a=10;

    }

    int calc_b(){

        b=a+10;

        return b;

    }

void print_val(){

    System.out.println(this.b);

}

public static void main(String args[]){

    static_variable v=new static_variable();

    v.calc_b();

    v.print_val();

    static_variable v1=new static_variable();

    v1.print_val();

}

}

Related questions

0 votes
asked May 5, 2021 in JAVA by SakshiSharma
0 votes
asked Oct 13, 2020 in JAVA by SakshiSharma
...