Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
823 views
in Technique[技术] by (71.8m points)

increment - Java preincrement and postincrement operators

public class Sample 
{
    public static void main(String[] args) throws Exception 
    {
        //part 1
        int i=1;
        i=i++;
        i=++i;
        i=i++;
        System.out.println(i);

        //part 2
        i=1;
        int a=i++;
        a=++i;
        a=i++;
        System.out.println(a+"
"+i);
    }
}

Output
2
3
4

Yesterday my friend asked this question. I little bit confused about this. part 1 prints the i value as 2. Post increment is not working here. But in the part 2, it works. I can understand the part 2 but i have confused in part 1. How actually it works? Can anybody make me understand?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Part one should print i = 2. This is because:

public class Sample 
{
    public static void main(String[] args) throws Exception 
    {
        //part 1
        int i=1;
        // i++ means i is returned (which is i = 1), then incremented, 
        //  therefore i = 1 because i is incremented to 2, but then reset 
        //  to 1 (i's initial value)
        i=i++;
        // i is incremented, then returned, therefore i = 2
        i=++i;
        // again, first i is returned, then incremented, therefore i = 2 
        //  (see first statement)
        i=i++;
        System.out.println(i);

        //part 2
        i=1;
        // first i is returned then incremented, so i = 2, a = 1
        int a=i++;
        // i is incremented then returned, so i = 3 and a = 3
        a=++i;
        // i is first returned, then incremented, so a = 3 and i = 4
        a=i++;
        System.out.println(a+"
"+i);
    }
}

Perhaps the simplest way to understand this is to introduce some extra variables. Here is what you have:

// i = i++
temp = i;
i = i + 1;
i = temp; // so i equals the initial value of i (not the incremented value)

// i = ++i;
i = i + 1;
temp = i;
i = temp; // which is i + 1

// i = i++
temp = i;
i = i + 1;
i = temp; // so i equals the previous value of i (not i + 1)

Notice the difference in order of when the temp variable is set--either before or after the increment depending on whether or not it's a post-increment (i++) or a pre-increment (++i).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...