Page 1 of 1

enthuware.ocajp.i.v8.2.1327: local variables

Posted: Tue Dec 20, 2016 9:48 am
by heleneshaikh
Hi,

Local variables don't have a default value. If the enhanced for-loop is not executed because of a false condition, how can the values be printed on line 5?

Code: Select all

 public static void main(String args[]) {
        int i;
        int j;
        for (i = 0, j = 0; j < i; ++j, i++) {
            System.out.println(i + " " + j);
        }
        System.out.println(i + " " + j); //5. Not initialised if loop doesn't run
    }

Re: enthuware.ocajp.i.v8.2.1327: local variables

Posted: Tue Dec 20, 2016 10:39 am
by admin
It is true that the loop body doesn't execute but the initialization section of a for loop always executes. The condition expression also executes at least once. If it returns false, the increment section doesn't execute.

Re: enthuware.ocajp.i.v8.2.1327: local variables

Posted: Tue Dec 20, 2016 10:51 am
by heleneshaikh
Thanks I really appreciate the quick reply. I understand it now.