-3

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?

Thomas Doyle
  • 113
  • 13
  • 5
    Well you could use `float[] array = { 1f, 0f };` instead... but basically, you can't have regular statements directly at the class level - only declarations and initializer blocks. – Jon Skeet Jan 04 '17 at 14:33

1 Answers1

1

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

beal
  • 435
  • 4
  • 15