Reputation: 51
In the below example:
class Foo {
public static String[] listofimages = new String[]{};
public static void main(String[] args) {
for(int i = 1; i <= 3; i++) {
listofimages[i] = //some image that I am adding to it
}
}
}
I am trying to access the newly modified listofimages variable in another class, Foobar (see below):
class Foobar(){
public void someClass{
Foo.listofimages //trying to access the newly modified listofimages variable with values in it
}
The above code is not working for me. I am confused on how to go about accessing the newly modified static variable listofimages, in a class that it is not declared in, class Foobar. Any help would be very much appreciated, thank you! :)
Upvotes: 0
Views: 96
Reputation: 878
At the time of class loading all the static variables are being initialized...in this case the array listofimages
is also initialized (though its empty) .
Now when you call the method someClass
of class Foobar
you are trying to access the initialized but empty listofimages
Solution:
Either make sure that the main method is called before you access the someClass
method so that your array can be populated or what you can do is initialize the array like:
public static String[] listofimages = {"a","b"};
Upvotes: 1
Reputation: 3266
When you refer to a class for the first time statically, all of its static variables are initialised. In this case, referencing Foo
has the effect of initialising the array. However, it is empty (as in has zero length).
Even though you add elements in the main method, it is never called before you reference listofimages
. Hence, it is still empty and referencing an index in an array that does not feature the index throws an Exception.
To fix the problem you would need to either:
main
is called before you access the array,However, seeing as you seem to be new to Java, I would like to point out some quirks with your design. If you have a static variable then you express that the variable should be static, as in having the same unique value for all instances of your class. In essence: for all Foo
instances, listofimages
should always have the same contents and all references should point to the same instance. When starting with Java, it is unlikely that you need this construct. May I suggest you simply declare it as public? Then you could move the initialisation into the constructor of Foo
and you would avoid the problem you face altogether.
Upvotes: 1
Reputation: 393936
If you are initializing the static array as shown, i.e. - listofimages = new String[]{}
, it is an empty array and listofimages[i]
will always throw an exception. You should initialize it with a positive length and only assign to valid indices of that array.
As for accessing that array from a different class, Foo.listofimages
should work (though Foo
class will have to be public in order to be visible to classes that belong to other packages).
Upvotes: 3