I know Java foreach loops are only meant to read values and not assign them, but I was wondering if they can call mutator methods on object. To find out I designed an experiment. Unfortunately the experiment crashes and I'm curious as to why.
public class test {
public static void main(String[] args)
{
    foo[] f = new foo[4];
    /*this would be a foreach loop, once I got the program working normally*/
    for(int i = 0; i < f.length; i++) {
        System.out.println(f[i].get());
        f[i].add();
        System.out.println(f[i].get());
    }
}
private class foo {
    foo() {
        int x = 5;
    }
    void add() {
        x++;
    }
    int get() {
        return x;
    }
    private int x;
}
}
Gives Exception in thread "main" java.lang.NullPointerException when I expected the output to be 5 6. Is it because the constructor to foo isn't being called? If so, how can it be called? Must foo be made a static class?
 
     
    