Return to site

☕🎓JAVA CERTIFICATION QUESTION: enum

· java,ocp

Given:

Which three of the following code statements compile successfully?

* Cola cola = new Cola("coca");

* String brand = Cola.PEPSI.brand;

* String[] brands = Cola.brand;

* Cola cola = Cola.valueOf("zevia");

* Cola[] colas = Cola.values();

#java #certificationquestion #ocp

https://www.udemy.com/course/ocp-oracle-certified-professional-java-developer-prep/?referralCode=54114F9AD41F127CB99A

* String brand = Cola.PEPSI.brand;

* Cola cola = Cola.valueOf("zevia");

* Cola[] colas = Cola.values();

Let's analyze each of the statements:

Cola cola = new Cola("coca");

This statement attempts to create a new instance of the Cola enum by providing a brand "coca" as an argument to its constructor.

Enum instances are typically created implicitly using the predefined values in the enum, so this statement is not valid.

It will not compile.

String brand = Cola.PEPSI.brand;

This statement attempts to access the brand property of the PEPSI enum constant.

Since brand is a non-private field defined in the enum.

This statement will compile successfully.

String[] brands = Cola.brand;

This statement tries to access a non-existent static field brand directly from the Cola enum type.

It's not a valid way to access the brand field for individual enum constants.

his statement will not compile.

Cola cola = Cola.valueOf("zevia");

This statement uses the valueOf method to get an enum constant by its name ("zevia").

If there is no enum constant with the name "zevia," it will throw an IllegalArgumentException at runtime.

It will compile successfully but may throw an exception at runtime.

Cola[] colas = Cola.values();

This statement uses the values method of the Cola enum to get an array of all enum constants.

This is a valid and commonly used way to access an enum's constants, and it will compile successfully.