Exception InInitializer Error for public static integer

I have a code where I need to call number of Jobs as public static integers from Size.txt file as follows:

public class GetJobs {
public static int Jobs = valueN(), inp = 4;

    public static void main(String[] args)throws IOException{
    ........................
    }

public static int valueN(){
            int n;
            File file = new File("C:\Data\Size.txt");
            String[] eachLine ;
            int[] MN = new int [inp];
            try{
                    Scanner input = new Scanner(file);              
                    eachLine = input.nextLine().split("\s+");      
                    for(int j=0; j<inp;j++){                    
                        MN[j]=Integer.parseInt(eachLine[j]);
                    }   
                    System.out.print("n");
                input.close();          
                }           
                catch(Exception e){             
                e.printStackTrace();            
            }           
            n=MN[0];
            return n;
    }

in Size.txt file the number of Jobs is the first element, the problem is I get an error when I run it. What is the problem?

the error is: Exception in thread “main” java.lang.ExceptionInInitializerError Caused by: java.lang.ArrayIndexOutOfBoundsException: 0

Answer

This is the problem:

public static int Jobs = valueN(), inp = 4;
...
public static int valueN(){
    ...
    int[] MN = new int [inp];
    ...
    n=MN[0];
}

When you run valueN(), inp is still 0. The initialization which will set inp to 4 will only occur after Jobs has been initialized when valueN() has returned. So you’re creating an empty array. You’re then trying to access element 0 of it. (You won’t actually have called Integer.parseInt, because your for loop with j will be comparing against inp, which is still 0…)

It’s not actually clear why you’re creating an array at all – you’re only returning the first value from the first line anyway, so I suggest you just return that without doing any other parsing. If you really want to create an array and parse multiple elements, either change the order of the initialization, or just move inp to inside your method. (It’s not clear what it’s meant to represent anyway…)

(I’d also recommend you stop catching all exceptions like that, but that’s a different matter.)

Note that running complex code in static initializers is generally a bad idea – it opens you up to this sort of problem. It would almost certainly be cleaner to move the call of valueN() to inside main.

Leave a Reply

Your email address will not be published. Required fields are marked *