counter with static variable, problem solved

Java Programming Language / Class, Object and Methods in java

1361

Program:

 class CounterClass{
static int count=0;//will get memory only once and retain its value

CounterClass(){
count++;
System.out.println(count);
}

public static void main(String args[]){

CounterClass c1=new CounterClass();
CounterClass c2=new CounterClass();
CounterClass c3=new CounterClass();

 }
}

/*
 Solution with static or class variable variable:

static variable will get the memory only once,
if any object changes the value of the static variable,
 it will retain its value.
 */

Output:

1
2
3
Press any key to continue . . .

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.