Why can't I give array elements a value outside of a method in Android Studio?

96 views Asked by At

Before my onCreate() method I can easily declare and initialise data types like int with the code

int number = 2;

however if I want to do this with an array, using code such as

float[] array = new float[2];
array[0] = 1;

the second line gives me an error. Why is this? Is there a way of initialising this array before the onCreate() method like I can do with other data types?

1

There are 1 answers

0
beal On

An Android Activity is just a normal class. There, regular statements can only be executed in:

methods

void x(){
    // do something nice here
}

instance contructors (that would be bad practise)

public class A {

    public A() {
       // you also could some stuff here
    }
}

"class constructors" / static blocks:

static {
    // here you can also do something
}

last possebility to set values to your array is on defining it:

float[] myArray = { 1f; 2f;};

I hope this can help you