Search code examples
javainitializationfield

Is there a way to initlalize a static field with a method?


How can I initialise an array of Strings within a class by using a method?

private static String[] strNrs2 = 
{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};  

private static String[] colo = arr();


private String[] arr(){
     String[] str99 = new String[strNrs2.length];
     for (int i = 0; i<strNrs2.length;i++){
       str99[i]= new StringBuilder(strNrs2[i]).reverse().toString();

    }
    return str99;
    }

I want this :

private static String[] strNrs2 = 
{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};

To look like this:

 private static String[] strNrs = 
 {"oreZ","enO","owT","eerhT","ruoF","eviF","xiS","neveS","thgiE","eniN"};

But I want to do it only once. Because I plan to loop through the method that will use the array, million of times. Therefore it will decrease my runtime speed considerably.

Full code:

  public class IntToStr {
  private static String[] strNrs2 = {"Zero","One","Two","Three","Four","Five","Six",
"Seven","Eight","Nine"};  

    public static String intToStr(int nr) {

        StringBuilder str = new StringBuilder("");

        while (nr>0) {
           int pop = nr%10;
            nr= nr/10;
            str.append(new StringBuilder(strNrs2[pop]).reverse().toString());  
//By using this str.append(strNrs[pop]); runtime will increase considerably.

        }
        return str.reverse().toString();
    }

    public static void main(String[] args) {

        for (int i = 0; i<10000000;i++)
            intToStr(5555555);
            System.out.println("Finished");

    }



} 

Solution

  • The following array initialization:

    private static String[] colo = arr();
    

    doesn't work because arr() is a non-static method, so it can't be called in the static context of initializing a static variable.

    You'll have to make arr() a static method in order for that static array initialization to work:

    private static String[] arr() {
        ...
    }