ElisaLyn ElisaLyn - 1 month ago 17
Java Question

Java static variables set by array

I'm new in learning java.
I have a question: Can static variables setting values by array?
I've tried 2 ways below, and need someone to help.
Thanks a lot.

Condition1:

public Class A{

public static String a, b, c;

public static void main(String [] arg){
set();
System.out.println(a + "\t" + b "\t" + c);
}

public static void set(){
String [] list = {a, b, c};
String [] var = {"apple", "pen", "pineapple"};

for(int i=0;i<list.length();i++){
list[i] = var[i];
}
}
}


output:
null

null

null


Condition2:

public Class A{

public static String a, b, c;
String [] list = {a, b, c};

public static void main(String [] arg){
set();
System.println(a + "\t" + b "\t" + c);
for(String items : list){
System.out.println(items);
}
}

public static void set(){
a = "apple";
b = "pen";
c = "pineapple";
}
}


output:
apple pen pineapple
null
null
null

Answer

Condition 1:

You're not actually setting the variables a, b and c in the set() method, this is why you're getting a null value as output. You are just creating a list inside your method.
To fix your code in your first condition, you can set your variables inside the set() while initialising the list:

a = list[0];
b = list[1];
c = list[2];

Condition 2:

You have initialised the list using the three variables before initialising them, hence you can see your results while printing the variables alone, but when printing the list they were all still null.
To fix your code in the second condition, don't initialise your list until the variables are.

public void set(){
    a = "apple";
    b = "pen";
    c = "pineapple";
    list = {a, b, c};
}

and you just declare it in the start like String [] list;

Comments