Bifalgorithm post · Computer science one · More Tricks

How do you declare and use an enumerated type in Java?

How do you declare and use an enumerated type in Java? (Computer science one · More Tricks) — "In the example, since the name of the enumeration is Day this de…

Ideas in this flowchart

  • The Day enumeration defines a type with restricted values and specific naming and access rules.
  • Because the enumeration is named Day, its declaration must be in a file named Day.java.
  • Variables of the Day type can be declared.
  • A Day variable can only take values such as SUNDAY, MONDAY, or other declared enumeration values.
  • Enumeration values belong to the Day class and must be accessed statically.
  • For example, today can be assigned the value Day.MONDAY.
  • The program can compare today with Day.SUNDAY or Day.SATURDAY to identify the weekend.
  • When the weekend condition is true, the program prints "Its the weekend!".
  • The enumerated type name follows the upper camel case convention used for classes.
  • Enumeration values follow an uppercase underscore convention.
  • If an enumeration value contains multiple words, underscores separate the words.
Feed/

How do you declare and use an enumerated type in Java?

No cover

Channel

Computer science one

1 page

"In the example, since the name of the enumeration is Day this declaration must be in a source file named Day.java. We can now declare variables of this type. The possible values it can take are restricted to SUNDAY, MONDAY, etc. and we can use these keywords in our program. However these values belong to the class Day and must be accessed statically. For example,\n\nDay today = Day.MONDAY;\n\nif(today == Day.SUNDAY || today == Day.SATURDAY) {\n\nSystem.out.println(\"Its the weekend!\");\n\n}\n\nNote the naming conventions: the name of the enumerated type follows the same upper camel casing that all classes use while the enumerated values follow an uppercase underscore convention. Though our example does not contain a value with multiple words, if it had, we would have used an underscore to separate them."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.