0

I created an enum array like this:

 enum MyEnums {
        FIRST, SECOND, THIRD, FOURTH;
 }
 public class MyEnumsTest {
     public static void main(String[] args) throws Exception {
            MyEnums[] myEnums = new MyEnums[4];
            for(int i = 0; i< myEnums.length; i++) {
                System.out.println(myEnums[i]);
            }
     }
 }

But why is the output null, null, null and null? And how can I get the element by myEnums[i].FIRST?

0

1 Answer 1

7

What you're doing here is creating an array of MyEnums, and the default value is null (you haven't set the values in the array).

If you wanted to print out the enum values you can use the values() method:

for(MyEnums en : MyEnums.values()) {
    System.out.println(en);
}

or (more like your original code)

for(int i = 0; i < MyEnums.values().length; i++) {
    System.out.println(MyEnums.values()[i]);
}

This prints:

FIRST
SECOND
THIRD
FOURTH
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your response, it is a quiz problem in my java lesson, I'm so confused that why the MyEnums[i] is null but I can use MyEnums[i].FIRST to get the element in this enum struct. It's so weird.
@ClarkQian It is because constants in an enum class are defined as public static final which means they belong to the enum/class itself (not the instance). Therefore you can access them even if an object is null. Take for example a class Test with 1 member public static final String NAME = "a";, you can create a variable like this Test t = null; but you can still call t.NAME and it will return a.
wow, I start to learn java one month ago, it is so amazing! thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.