954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

postfix and prefix

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); 	
         }

}
solomon_13000
Junior Poster in Training
88 posts since Jul 2009
Reputation Points: 24
Solved Threads: 0
 

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.

Thijk
Newbie Poster
16 posts since May 2011
Reputation Points: 10
Solved Threads: 3
 

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

stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
 

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.

AnkitKumar
Newbie Poster
20 posts since Jun 2009
Reputation Points: 14
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: