Below is code taken from Sun
Java Tutorial
. From my reading of the code the first time this loop executes should it not populate cards[1] with the first card skipping cards[0]? I've tested the code in eclipse and it seems to work properly first populating card[0] so I'm hoping somebody can explain why i++ is not read as 1 the first time the loop executes?

public class Deck3 {
    private static Card3[] cards = new Card3[52];
    public Deck3() {
        int i = 0;
        for (Suit suit : Suit.values()) {
            for (Rank rank : Rank.values()) {
                cards[i++] = new Card3(rank, suit);
            }
        }
    }
}
Member Avatar for soUPERMan

Because counting starts from 0 .

int i = 0;

Because counting starts from 0 .

int i = 0;

Yes but the first call is cards[i++] so why does this not equate to cards[0++] which is cards[1]? Is there a special rule when using the incremental operator within an array index that the incremental operator is only applied after this statement is executed?

int i = 0;
i++;

In this instance i would be 1 after statement executes would it not? Does the ++ only get applied after the statement meaning that the code is shorthand for

cards[i] = new Card3(rank, suit);
i++;

I think I found the answer in a javascript tutorial, I was reading i++ as immediately applied, were the code

cards[++i]

this would result in the problem I thought I was seeing as far as I can tell

The unary ++ operator comes in preincrement and postincrement flavors. You used (as you noticed) the postincrement version, which does the ++ after it reads the variable.

j=i++; is equivalent to

j=i; i+=1;


If you did a preincrement, you would indeed start from 1.
The preincrement operator is like this:

++i;

j=++i; is equivalent to

i+=1; j= i;

Thanks again Jon, just when you think you have a handle on the basics some shorthand code comes along and proves you wrong. All part of the journey I suppose :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.