Why is the output 10 and not 9?. According to my understanding the count value is assign to b. Then the count value increment. Hence the output should be 9 instead of 10. However in this case the output is 10. Why?.

package com.nowhere.blogger.core.junit;

public class Bunnies {
	
	static int count = 0;
	Bunnies(){
		while(count < 10) new Bunnies(++count); //prefix
	}
	Bunnies(int x) {super();}
	public static void main(String[] args){
		new Bunnies();
		new Bunnies(count);
                  int b = count++; //postfix
		System.out.println(b); 	
         }

}

When you start counting to 0 and make it go to 9, you get 10 values. (0,1,2,3,4,5,6,7,8 and 9)

If you want it to be 9, you should change your while-loop to

while(count < 9) new Bunnies(++count);

or keep the 10 in your loop and initialize count as 1 instead of 0.

you get value 10 since, as Thijk posted, the expression count < 10 will only return false when count = 10 (or count > 10).

the next increment is a postfix, so count will only be incremented after the value of b is set, so when you're printing your line:

count == 11
b == 10

when b becomes 9 it is checked in while loop likes while(9<10) then loop returns true because 9 is less than 10 after that b is incremented & it become 10 after that it will check condition in while loop like while(10<10) then it returns false or your program print b=10 & program get terminate.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.