Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store recent values in a variable in java programming?

Tags:

java

In my java program,I need to store the recent values in a variable and my code is as shown below

public class Exmp2 
{

        int noOfInstances;
    public Exmp2() 
    {
        noOfInstances++;
    }
    public static void main(String[] args){
        Exmp2 e1=new Exmp2();
        System.out.println("No. of instances for sv1 : " + e1.noOfInstances);

        Exmp2 e2=new Exmp2();
        System.out.println("No. of instances for sv1 : "  + e2.noOfInstances);
        System.out.println("No. of instances for st2 : "  + e2.noOfInstances);

        Exmp2 e3=new Exmp2();
        System.out.println("No. of instances for sv1 : "  + e3.noOfInstances);
        System.out.println("No. of instances for sv2 : "  + e3.noOfInstances);
        System.out.println("No. of instances for sv3 : "  + e3.noOfInstances);
    }
}

My output should be 1 2 2 3 3 3 but am getting 1 1 1 1 1 1 can you give solution?

like image 358
Rajendra_Prasad Avatar asked Mar 28 '13 06:03

Rajendra_Prasad


1 Answers

Declare your noOfInstances variable as static.

static int noOfInstances;

Since its not static, for every new Exmp2() a noOfInstances is created for that instance, with the default value as 0.

like image 179
Rahul Avatar answered Sep 28 '22 06:09

Rahul