Static Class not loaded

5.7k views Asked by At

Im familiar with C#, learning static class in Java nowadays. in the code below, I assumed if staticClass constructor is already initialized at startup. but it is not. When debug cursor reach the breakpoint of first for loop in main method. I get an error "staticClass not loaded".

Question: is there a way to execute static class constructor before main method executed? or why its not loaded ? similar static class is loaded in C# at startup. but in java ? consider that this is a not working code. as an java expert, how you could rewrite this code ? as it should corrected.

public class Main {

    public static class staticClass
    {
        public static int myArray[];

        public staticClass()
        {
            myArray=new int[10];
        }

        public static int NextUnique()
        {
            int r=(int)(Math.random()*10);
            return r;
        }
    }
    //=new int[10];
    public static void main(String[] args) throws ClassNotFoundException {

        for (int i=0;i<staticClass.myArray.length;i++)
            staticClass.myArray[i]=  staticClass.NextUnique();

        for(int i=0;i<staticClass.myArray.length;i++) {
            String msg= MessageFormat.format("{0}. value= {1}",i,staticClass.myArray[i]);
            System.out.println(msg);
        }
    }
}
2

There are 2 answers

4
Atilla Ozgur On BEST ANSWER

You need to use a static static initialization block (constructor) for this purpose. Instead of

 public staticClass()
    {
        myArray=new int[10];
    }

use

 static
    {
        myArray=new int[10];
    }

Your constructor right now is instance constructor. It works whenever you use new operator. See static constructor in c# and static initialization block (constructor) java

2
JensS On

You can just initialize the array like this:

    public static int myArray[] = new int[10];