You need to create array1
as a class variable in order for the whole class to have access to it. As a general rule of thumb, the scope of a variable last between the two brackets {
}
it is initialized in. In your two methods, you initialize array1 in those method, so the scope of array1 is in those methods only.
Change the code to something like this:
public class JavaApplication2 {
int[] array1;
public JavaApplication2()
{
}
public static void main(String[] args) {
JavaApplication2 obj = new JavaApplication2();
obj.method();
System.out.print(obj.array1[1]);
}
public void method()
{
array1 = new int[]{1, 1, 1, 1, 1};
}
}
It would be even better to initalize array1[] as private and have a getter method for it like this:
public class JavaApplication2 {
private int[] array1;
public JavaApplication2()
{
}
public static void main(String[] args) {
JavaApplication2 obj = new JavaApplication2();
obj.method();
System.out.print(obj.getArray1().[1]);
}
public void method()
{
array1 = new int[]{1, 1, 1, 1, 1};
}
public void getArray1()
{
return array1;
}
}