Will this ever result in a stack overflow error?

Posted by David on Stack Overflow See other posts from Stack Overflow or by David
Published on 2010-04-14T21:41:17Z Indexed on 2010/04/14 21:43 UTC
Read the original article Hit count: 232

Filed under:
|
|

Will incrementing the instance variables of an object ever lead to a stack overflow error?

For example:

This method (java) will cause a stack overflow error:

class StackOverflow {
    public static void StackOverflow (int x) 
    {
        System.out.println (x) ; 
        StackOverflow(x+1) ; 
    } 

    public static void main (String[]arg) { StackOverflow (0) ; 
} 

but will this?: (..... is a gap that i've put in to shorten the code. its long enough as it is.)

import java.util.*;
class Dice 
{ 
    String name ; 
    int x ; 
    int[] sum ;  

....

public Dice (String name) 
{ 
    this.name = name ; 
    this.x = 0 ; 
    this.sum = new int[7] ; 
}

....

public static void main (String[] arg) 
{
    Dice a1 = new Dice ("a1") ; 
    for (int i = 0; i<6000000; i++) 
    {
        a1.roll () ;
        printDice(a1) ; 
    } 
}

....

    public void roll () 
    {
        this.x = randNum(1, this.sum.length) ; 
        this.sum[x] ++ ;
    }

    public static int randNum (int a, int b) 
    {
        Random random = new Random() ;
        int c = (b-a) ;
        int randomNumber = ((random.nextInt(c)) + a) ;
        return randomNumber ;
    }

    public static void printDice (Dice Dice) 
    { 
        System.out.println (Dice.name) ; 
        System.out.println ("value: "+Dice.x) ; 
        printValues (Dice) ; 
    } 

    public static void printValues (Dice Dice) 
    { 
        for (int i = 0; i<Dice.sum.length; i++) 
        System.out.println ("#of "+i+"'s: "+Dice.sum[i]) ; 
    } 

}

The above doesn't currently cause a stack overflow error but could i get it too if i changed this line in main: for (int i = 0; i<6000000; i++) so that instead of 6 million something sufficiently high were there?

© Stack Overflow or respective owner

Related posts about java

Related posts about stackoverflow