Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

predict output problem related to ++i i++

class output {

 public static void main(String args[])

    {
        char c[]={'a', '1', 'b' ,' ' ,'A' , '0'};

        for (int i = 0; i < 5; ++i)

        {
            if(Character.isDigit(c[i]))

                System.out.println(c[i]+" is a digit");

            if(Character.isWhitespace(c[i]))

                System.out.println(c[i]+" is a Whitespace character");

            if(Character.isUpperCase(c[i]))

                System.out.println(c[i]+" is an Upper case Letter");

            if(Character.isLowerCase(c[i]))

                System.out.println(c[i]+" is a lower case Letter");

            i=i+3;
        }
     }

}

what is the output

a) a is a lower case Letter is White space character

b) b is a lower case Letter is White space character

c) a is a lower case Letter A is a upper case Letter

d) a is a lower case Letter 0 is a digit

the answer is C

but i dont understand i=0+3 , i should be 3 , which is ' ' (white space),

does ++i mean it increments right away which makes i = 1 at that point, if that is the case, why the loop will be executed as i = 0?

thanks.

Yes, i = 0 + 3 = 3 happens during the very first iteration, but notice that '++i' (the loop index increment expression, '++i', at the end of the 'for' loop definition) gets executed at the end of the first iteration of the loop.

So, i = 3 + 1 = 4. And, as per the array 'c[]' definition, c[4] = 'A'. And, that explains the Output answer 'C'.

1 Answer

Yes, i = 0 + 3 = 3 happens during the very first iteration, but notice that '++i' (the loop index increment expression, '++i', at the end of the 'for' loop definition) gets executed at the end of the first iteration of the loop.

So, i = 3 + 1 = 4. And, as per the array 'c[]' definition, c[4] = 'A'. And, that explains the Output answer 'C'.