Computer Science
Java Enums
Java Enums are a special data type that allow developers to define a set of named constants. They are used to represent a fixed number of possible values, such as the days of the week or the months of the year. Enums provide type safety and can be used in switch statements.
Written by Perlego with AI-assistance
Related key terms
1 of 5
5 Key excerpts on "Java Enums"
- eBook - ePub
Kotlin In-Depth [Vol-I]
A Comprehensive Guide to Modern Multi-Paradigm Language
- Aleksei Sedunov(Author)
- 2020(Publication Date)
- BPB Publications(Publisher)
HAPTER 6Using Special-Case Classes
I n this chapter, we will discuss special kinds of classes designed to simplify implementation of some common programming patterns. Namely, we’ll address the usage of enums to describe types with a restricted set of instances, the concise representation of data with data classes, and experimental lightweight wrappers with almost zero runtime overhead.Structure
- Enum classes
- Data classes
- Inline classes
Objective
Learn to use special varieties of classes such as enums and data classes to solve common programming tasks. Get a basic understanding of inline classes and their usage on the example of unsigned integer types.Enum classes
An enum (short of enumeration) class is a special variety of class which can represent a limited set of predefined constants. The simplest form is just a list of constant names enclosed inside the enum class body:enum class WeekDay { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } fun WeekDay.isWorkDay() = this == WeekDay.SATURDAY || this == WeekDay.SUNDAY fun main() { println(WeekDay.MONDAY.isWorkDay()) // false println(WeekDay.SATURDAY.isWorkDay()) // true }Enums allow more type-safe representation of limited value sets as compared to, say, integers or strings since you don’t have to check whether a value in question is out of possible range. The compiler ensures that any variable of a particular enum type can take only one of the values specified in its body.Java versus Kotlin: Kotlin enums are defined with a pair of the keyword enum class as opposed to just enum in Java. The enum keyword itself is soft and can be used as an identifier in any other context.Note that being compile-time constants enum values are usually written in upper case.Enums are somewhat similar to object declarations, in a sense that they define a set of global constants representing instances of a particular type. Similar to objects, they are not permitted in contexts where there is no guarantee that such definition can be available as a global constant. You can’t, for example, put an enum definition into an inner class or a function body: - eBook - PDF
- Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser(Authors)
- 2014(Publication Date)
- Wiley(Publisher)
A slightly better programming style is to define static constants (with the final keyword), to make the associations, such as: static final int MON = 0; static final int TUE = 1; static final int WED = 2; ... because then it becomes possible to make assignments such as today = TUE, rather than the more obscure today = 1. Unfortunately, the variable today is still declared as an int using such a programming style, and it may not be clear that you intend for it to represent a day of the week when storing it as an instance variable or sending it as a parameter. Java supports a more elegant approach to representing choices from a finite set by defining what is known as an enumerated type, or enum for short. These are types that are only allowed to take on values that come from a specified set of names. They are declared as follows: modifier enum name { valueName 0 , valueName 1 , ..., valueName n−1 }; where the modifier can be blank, public, protected, or private. The name of this enum, name, can be any legal Java identifier. Each of the value identifiers, valueName i , is the name of a possible value that variables of this enum type can take on. Each of these name values can also be any legal Java identifier, but the Java convention is that these should usually be capitalized words. For example, an enumerated type definition for days of the weak might appear as: public enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }; Once defined, Day becomes an official type and we may declare variables or pa- rameters with type Day. A variable of that type can be declared as: Day today; and an assignment of a value to that variable can appear as: today = Day.TUE; 1.4. Java Expressions 23 1.4 Java Expressions Variables and constants are used in expressions to define new values and to modify variables. In this section, we discuss how expressions work in Java in more detail. Expressions involve the use of literals, variables, and operators. - eBook - ePub
Kotlin In-Depth
A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile
- Aleksei Sedunov(Author)
- 2022(Publication Date)
- BPB Publications(Publisher)
HAPTER 6Using Special-Case Classes
In this chapter, we will discuss special kinds of classes designed to simplify the implementation of some common programming patterns. Namely, we’ll address the usage of enums to describe types with a restricted set of instances, the concise representation of data with data classes, and experimental lightweight wrappers with almost zero runtime overhead.Structure
- Enum classes
- Data classes
- Inline classes
Objective
After reading this chapter, you will learn to use special varieties of classes such as enums and data classes to solve common programming tasks. Get a basic understanding of inline classes and their usage on the example of unsigned integer types.Enum classes
An enum (short of “enumeration”) class is a special variety of class which can represent a limited set of predefined constants. The simplest form is just a list of constant names enclosed inside the enum class body:enum class WeekDay {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }fun WeekDay.isWorkDay() =!(this == WeekDay.SATURDAY || this == WeekDay.SUNDAY)fun main() {println(WeekDay.MONDAY.isWorkDay()) // true println(WeekDay.SATURDAY.isWorkDay()) // false }Enums allow more type-safe representations of limited value sets as compared to, say, integers or strings since you don’t have to check whether a value in the question is out of possible range. The compiler ensures that any variable of a particular enum type can take only one of the values specified in its body.Java vs. Kotlin : Kotlin enums are defined with a pair of keyword enum class as opposed to just enum in Java. The enum keyword itself is soft and can be used as an identifier in any other context.Note that compile-time constants enum values are usually written in upper case.Enums are somewhat similar to object declarations in a sense that they define a set of global constants representing instances of a particular type. Similarly to objects, they are not permitted in contexts where there is no guarantee that such a definition can be available as a global constant. You can’t, for example, put an enum definition into an inner class or function body: - eBook - PDF
C++ Programming
From Problem Analysis to Program Design
- D. Malik(Author)
- 2017(Publication Date)
- Cengage Learning EMEA(Publisher)
The following, however, are legal enumeration types: enum grades {A, B, C, D, F}; enum places {FIRST, SECOND, THIRD, FOURTH}; If a value has already been used in one enumeration type, it cannot be used by any other enumeration type in the same block. The same rules apply to enumeration types declared outside of any blocks. Example 7-4 illustrates this concept. EXAMPLE 7-4 Consider the following statements: enum mathStudent {JOHN, BILL, CINDY, LISA, RON}; enum compStudent {SUSAN, CATHY, JOHN, WILLIAM}; //illegal Suppose that these statements are in the same program in the same block. The second enumeration type, compStudent, is not allowed because the value JOHN was used in the previous enumeration type mathStudent. Declaring Variables Once a data type is defined, you can declare variables of that type. The syntax for declaring variables of an enum type is the same as before: The statement: enum sports {BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER, VOLLEYBALL}; defines an enumeration type called sports. The statement: sports popularSport, mySport; declares popularSport and mySport to be variables of type sports. Assignment Once a variable is declared, you can store values in it. Assuming the previous declaration, the statement: popularSport = FOOTBALL; stores FOOTBALL in popularSport. The statement: mySport = popularSport; copies the value of popularSport into mySport. dataType identifier, identifier,...; Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. - eBook - PDF
- Ivor Horton(Author)
- 2005(Publication Date)
- Wrox(Publisher)
You can conclude from this that for casting purposes you should always use the instanceof operator to check the type of a reference. You only need to resort to checking the Class object corresponding to a reference when you need to confirm the exact type of the reference. More on Enumerations When I introduced enumerations in Chapter 2, I said that there was more to enumerations than simply a type with a limited range of integer values. In fact, an enumeration type is a special form of class. When you define an enumeration type in your code, the enumeration constants that you specify are created as instances of a class that has the Enum class, which is defined in the java.lang package, as a superclass. The object that corresponds to each enumeration constant stores the name of the constant in a field, and the enumeration class type inherits the toString method from the Enum class. The toString() method in the Enum class returns the original name of the enumeration constant, so that’s why you get the name you gave to an enumeration constant displayed when you output it using the println() method. You have seen that you can put the definition of an enumeration type within the definition of a class. You can also put the definition is a separate source file. In this case you specify the name of the file con- taining the enumeration type definition in the same way as for any other class type. An enumeration that you define in its own source file can be accessed by any other source file in exactly the same way as any other class definition. 302 Chapter 6 An object representing an enumeration constant also stores an integer field. By default, each constant in an enumeration will be assigned an integer value that is different from all the other constants in the enu- meration. The values are assigned to the enumeration constants in the sequence in which you specify them, starting with zero for the first constant, 1 for the second, and so on.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.
![Book cover image for: Kotlin In-Depth [Vol-I]](https://img.perlego.com/book-covers/1681462/9789389328585_300_450.webp)



