How can i use it for printing 11 12 13?I want this result normally using static initializer block without using for loop | Core Java Forum
S
Shinia Posted on 28/11/2021

package com.programming.java;

public class Counter {
//non-static variable
int count1=10;
//static variable
static int count2=10;
Counter()
{

count1++;
System.out.println("the value of count variable is " + count1);

}
static {
System.out.println("static initializer block");
for(count2=10;count2<=13;count2++)
{
System.out.println("the value of count variable is " + count2);

}

}
public static void main(String[] args) {
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();

}
}


Y
Yogesh Chawla Replied on 28/11/2021

Every object carries a unique value of any non-static variable so output is 11,11 and 11 for all three objects.

And every static variable is shared by all objects so parallely if you want 11 12 and 13 for static variables, we need static method to increment static variable and call static method three times either with three different objects(which is not recommended) or directly with class name.

public class Counter {
	//non-static variable
	int count1 = 10;
	
	//static variable
	static int count2 = 10;

	Counter() {
		count1++;
		System.out.println("the value of count1 variable is " + count1);
	}
	
	static void valueIncrement() {
		count2++;
		System.out.println("the value of count2 variable is " + count2);
	}
	public static void main(String[] args) {
		Counter c1 = new Counter();
		Counter c2 = new Counter();
		Counter c3 = new Counter();
		
		//not recommended
		c1.valueIncrement();
		c2.valueIncrement();
		c3.valueIncrement();
		
		//For desired output of static variables
		Counter.valueIncrement();
		Counter.valueIncrement();
		Counter.valueIncrement();

	}
}


S
Shinia Replied on 06/12/2021

got it...thank you!