Frage

I believe that this question is different, because the other question was asking how the numbers were being incremented inside the println(). The accepted answer in the other question was not explaining that postfix increments the value after it is printed.

I have been reading from the Big Index, and I understand how and when to use postfixes, but I had no idea that prefixes existed. What does it mean when it says that 6 gets printed twice in this code? I thought that it added to the integer.

class PrePostDemo {
    public static void main(String[] args){
        int i = 3;
        i++;
        // prints 4
        System.out.println(i);
        ++i;               
        // prints 5
        System.out.println(i);
        // prints 6
        System.out.println(++i);
        // prints 6
        System.out.println(i++);
        // prints 7
        System.out.println(i);
    }
}

Why would it not print 4, 5, 6, 7, 8?

War es hilfreich?

Lösung

Prefix will perform the addition/subtraction before executing the current statement of code. Postfix will perform it afterwards.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top