0

I'm trying to create a class with static variables, but I'm not sure how to set the variables before runtime. This is what I'm attempting to do...

public class Defaults {

public static String[] abc = new String[2];

public static void functionToExecuteBeforeRuntime{

    abc[0] = "a";
    abc[1] = "b";
    abc[2] = "c";

}

}

It's supposed to set abc using functionToExecuteBeforeRuntime before runtime so other classes can access it with Defaults.abc,however it is never executed. How can I achieve this? Any help appreciated

-oh i'm not sure if this makes a difference but I don't think with andriod I can use the public static main() guy

2 Answers 2

1

For that example, you could just initialize it there, like:

public static String[] abc = new String[]{"a", "b", "c"};

For just a general way of doing complex initialization for your static fields, I'm not sure, but I believe Android has Static Initializer Blocks, which work like:

public class Test
{
 public static String[] stuff = new String[2];
 static
 {
  stuff[0] = "Hi";
  stuff[1] = "Bye";
 }
}

Or you could use static functions to do, basically, the same thing.

public class Test
{
 public static String[] stuff = initializeStuff();
 public static String[] initializeStuff()
 {
  String[] arr = new String[2];
  arr[0] = "Hi";
  arr[1] = "Bye";
  return arr;
 }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Put it into a static initialization block of code like so:

private static String[] stuff;

static {
  stuff = new String[] {"1", "2"};
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.