title: Stack Overflow Error in a Self Calling Function in Java (Number of Islands)
body: <p>I did some research on what causes a stack overflow errors, and I can conclude it is being caused by a recursive function in a program that is supposed to "count the number of islands" in an array. I understand what is causing the issue, but not sure why this is happening, or my main question is what to actually do about it. I found that if I slow down the program by having it repeatedly printing out something to the console, it works, but it takes forever to complete. Is there a way I can keep the program speed without the error, or a better way to solve the problem (search up "number of islands" to find the problem). Also, the array is two dimensional with a size of 1050 by 800.</p>
  
  <pre><code>public class NumOfIslands {
    static boolean[][] dotMap = new boolean[1050][800];
    static boolean visited[][] = new boolean[1050][800];
    static int total = 0;
    public static void main(String args[]) {
      defineArrays();
      run();
    }
    public static void findObjects(int xCord, int yCord) {
      for(int y = yCord - 1; y &lt;= yCord + 1; y++) {
        for(int x = xCord - 1; x &lt;= xCord + 1; x++) {
          if(x &gt; -1 &amp;&amp; y &gt; -1 &amp;&amp; x &lt; dotMap[0].length &amp;&amp; y &lt; dotMap.length) {
            if((x != xCord || y != yCord) &amp;&amp; dotMap[x][y] == true &amp;&amp; visited[x][y] != true) {
              visited[x][y] = true;
              findObjects(x,y);
              //System.out.println("test");
            }
          }
        }
      }
    }
    public static void defineArrays() {
      for(int y = 0; y &lt; 800; y++) {
        for(int x = 0; x &lt; 1050; x++) {
          dotMap[x][y] = true;
        }
      }
    }
  
    public static int run() {
      //dotMap = DisplayImage.isYellow;
      System.out.println(dotMap.length + " " + dotMap[0].length);
      int objects = 0;
      for(int y = 439; y &lt; 560/*dotMap[0].length*/; y++) {
        for(int x = 70; x &lt; 300/*dotMap.length*/; x++) {
          if(dotMap[x][y] == true &amp;&amp; visited[x][y] != true) {
            visited[x][y] = true;
            objects++;
            findObjects(x,y);
          }
        }
      }
      System.out.println("total" + total);
      System.out.println(objects);
      return objects;
  
    }
  }
  </code></pre>