In here:
The output should be 9, Why is 10?
Can anybody explain me step by step?
In here:
The output should be 9, Why is 10?
Can anybody explain me step by step?
The while
loop exits when count
is 10 (9 is still less than 10).
Then you println
count
, whose value is 10.
Finally you increment its value which, after printing, it's 11.
This part:
Pangool(){
while(count < 10)
new Pangool(++count)
}
Will increment count
from 0 all the way to 10.
Then at here:
public static void main (String[] args){
new Pangool();
new Pangool("Pangool");
System.out.println(count++);
}
It will print the current value of count
, then increment count
. This line:
System.out.println(count++);
is equivalent to:
System.out.println(count);
count = count + 1;
If you write out the code and add a few print statements, you can see the flow of the value:
before: 0
after: 1
before: 1
after: 2
before: 2
after: 3
before: 3
after: 4
before: 4
after: 5
before: 5
after: 6
before: 6
after: 7
before: 7
after: 8
before: 8
after: 9
before: 9
after: 10
10
10
11
Lemme walk you through it:
First it calls new Pangool()
which starts the loop
count is initialized to 0
we now call Pangool(++count)
, which increases count to 1 and passes the value of 1 (count++ would have passed 0 and changed it to 1 afterwards). Count is 1.
this calls the Pangool(int)
constructor which does nothing
the loop continues with the value increasing, up to where count is 9, on this loop we now call Pangool(++count)
which increases count to 10.
Now we're done with Pangool()
and count is 10
Now we call Pangool("Pangool")
which invokes the string constructor which does nothing to count, still 10.
Now we call System.out.println(count++)
, this prints count at 10, then changes count to 11.
System.out.println(count)
would print 11 after.
check out pre-fix and post-fix operators here:
It's because you start the count at 0 and stop at 9, 9 included. Your count start at 0 and increments by 1 for about 10 times. If you count number by number, 0 1 2 3 4 5 6 7 8 9, you can see that there are 10 numbers.