Home / Programs / counter without static variable, problem
🚀 Programming Example

counter without static variable, problem

👁 28,120 Views
💻 Practical Program
📘 Step Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

💻 Program Code

 class CounterClass{
int count=0;//will get memory when instance is created

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

public static void main(String args[]){

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

 }
}

/*
 problem with instance variable:

 instance variable gets the memory at the time of object creation,
 each object will have the copy of the instance variable, if it is
 incremented, it won't reflect to other objects. So each objects will
 have the value 1 in the count variable.
 */
                        

🖥 Program Output

1
1
1
Press any key to continue . . .
                            
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.