Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

For Loop Syntax

Can anyone explain what i --> 0 is doing? I don't understand the syntax.

public class Main { public static void main(String[] args) { int N = 77777777; long t;

    {
        StringBuffer sb = new StringBuffer();
        t = System.currentTimeMillis();
        for (int i = N; i --> 0 ;) {
            sb.append("");
        }
        System.out.println(System.currentTimeMillis() - t);
    }
}

}

1 Answer

You know how you can increase or decrease a variable by using ++ or --? That is what's being done here. It's just spaced in a confusing manner. There is a space between i and the --, and no space between the -- and the less than symbol, since Java doesn't really care all that much about how you space your code so long as you place the semicolon in the right place odd spacing like that is technically valid.

Changing the spacing like this:

for (int i = N; i-- > 0;) {
    sb.append("");
}

Makes it slightly clearer what is actually happening. In reality it's just a quicker (but harder to read) way of writing this:

for (int i = N; i > 0; i--) {
    sb.append("");
}

They essentially just merged the comparison of i and the subtraction of i into one step, which makes the code smaller. I would not recommend writing code in this style though as it will likely cause more confusion than benefit.