Java-Static Variables

Static Variables

Let us assume that we want to define a member that is common to all the objects and accessed without using a particular object. That is, the member belongs to the class as a whole rather than the objects created from the class. Such members can be defined by static keyword. The members that are declared static as are called static members. The static variable will keep same value for every object ( that is not unique for each object). The static variable gets memory only once in class area at the time of class loading. A single copy to be shared by all instances of the class.


Program Source

class Data {
    static int data1 =10;
    int data2 = 20;

public class Javaapp {
    public static void main(String[] args) {
        Data d1 = new Data();
        d1.data1 = 50;
        d1.data2 = 100;
        System.out.println("d1.Data1 = "+d1.data1);
        System.out.println("d1.Data2 = "+d1.data2);
        Data d2 = new Data();
        System.out.println("d2.Data1 = "+d2.data1);
        System.out.println("d2.Data2 = "+d2.data2);

Leave a Comment