0

In here:

enter image description here

The output should be 9, Why is 10?

Can anybody explain me step by step?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Sajad
  • 2,273
  • 11
  • 49
  • 92

4 Answers4

5

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.

HAL9000
  • 3,562
  • 3
  • 25
  • 47
  • This is incorrect, the value of count is 9, but then count is called with ++ before being passed to Pangool() constructor. – SpacePrez Jan 08 '14 at 22:12
2

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
2

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:

Java: Prefix/postfix of increment/decrement operators?

Community
  • 1
  • 1
SpacePrez
  • 1,086
  • 7
  • 15
0

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.

MrSilent
  • 564
  • 10
  • 28