Enumerated types are an ideal representation for small collections of values that can be enumerated. Enumerated types also define an order on the values, which can sometimes be useful.
/**
* Copyright (C) 2024 by Martin Robillard.
* See https://codesample.info/about.html
*/
package essentials;
/**
* Represents a given day of the week.
*/
Day
{
, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
/**
* This class is a mock-up that illustrates what enumerated correspond
* to in terms of basic Java concepts. A value of an enumerated type
* is a specific object referenced through a constant defined in the class.
*/
class FakeDayEnum //
{
public static final FakeDayEnum MONDAY = new FakeDayEnum();
public static final FakeDayEnum TUESDAY = new FakeDayEnum();
public static final FakeDayEnum WEDNESDAY = new FakeDayEnum();
// ... and so on
FakeDayEnum() {}
}
/**
* Enumerated types can also store values.
*/
enum Month
{
JANUARY, FEBRUARY(28), MARCH(31), APRIL(30), MAY(31), JUNE(30), JULY(31),
AUGUST(31), SEPTEMBER(30), OCTOBER(31), NOVEMBER(30), DECEMBER(31)
// This is for illustration purposes: we don't worry about leap years
int aNumberOfDays;
Month(int pNumberOfDays)
{
aNumberOfDays = pNumberOfDays;
}
public int numberOfDays()
{
return aNumberOfDays;
}
public String
{
return name().charAt(0) + name().substring(1).toLowerCase();
}
public Month next()
{
return Month.values()[(ordinal()+1) % Month.values().length];
}
}
/**
* Demonstrates some common usage patterns for enumerated types.
*/
public class EnumTypes
{
public static void main(String[] args)
{
for (Day day : Day.)
{
System.out.println(day);
}
// Obtain a month by string value
Month month = Month.("APRIL");
System.out.println(String.format("%s has %d days", month.asString(), month.numberOfDays()));
System.out.println(String.format("%s follows %s", month.next().asString(), month.asString()));
}
}
The simplest enum
declaration consists of a list of names, one for each value.
Since the names refer to constants, we usually set in all caps by convention.
The simplest enum
declaration consists of a list of names, one for each value.
Since the names refer to constants, we usually set in all caps by convention.
Values of an enumerated type are constants, usually set in all caps.
Values of an enumerated type are constants, usually set in all caps.
In an enum type declaration includes fields or methods, the list of constants must be terminated by a semicolon. Otherwise, it is not necessary.
In an enum type declaration includes fields or methods, the list of constants must be terminated by a semicolon. Otherwise, it is not necessary.
The values()
static method returns an array of all the enum values for a type in declaration order.
This is a special implicitly declared method automatically
added by the compiler. For this reason, there is no Javadoc for it.
The values()
static method returns an array of all the enum values for a type in declaration order.
This is a special implicitly declared method automatically
added by the compiler. For this reason, there is no Javadoc for it.
The valueOf
static method returns an enum value given its string representation. Similarly to values()
,
it is an implicitly-declared method inserted by the compiler.
The keyword enum
defines an enumerated type. An enumerated type is a reference type,
similar to a class.
The keyword enum
defines an enumerated type. An enumerated type is a reference type,
similar to a class.
The private constructor in this mock-up illustrates the fact that enum types cannot be instantiated. In practice, additional mechanisms ensure that "An enum type has no instances other than those defined by its enum constants." The only instances of the type that exist are those available through the public static fields of the class (that is, the global constants).
The private constructor in this mock-up illustrates the fact that enum types cannot be instantiated. In practice, additional mechanisms ensure that "An enum type has no instances other than those defined by its enum constants." The only instances of the type that exist are those available through the public static fields of the class (that is, the global constants).
Fields of enum types do not have to be private and final, but it is strongly recommended. Being able to change the values within enum constants would, in many cases, lead to confusing code.
Fields of enum types do not have to be private and final, but it is strongly recommended. Being able to change the values within enum constants would, in many cases, lead to confusing code.
Enum constructors must be declared private.
This method returns a string of the constant's name in title case. An alternative design would be to
override Enum#toString()
instead. However, the Javadocs for Enum#toString()
state "This method may be overridden, though it typically isn't necessary or desirable.".
Here, we don't override it so that automatic conversion of instances to String retain the original name
of the constant (in our case, in all caps).
This method returns a string of the constant's name in title case. An alternative design would be to
override Enum#toString()
instead. However, the Javadocs for Enum#toString()
state "This method may be overridden, though it typically isn't necessary or desirable.".
Here, we don't override it so that automatic conversion of instances to String retain the original name
of the constant (in our case, in all caps).
A common operation on enumerated types is to obtain the next (or previous) one in the sequence. As of Java 21, this operation is not supported by the JDK, but it can be easily implemented.
A common operation on enumerated types is to obtain the next (or previous) one in the sequence. As of Java 21, this operation is not supported by the JDK, but it can be easily implemented.
If an enum type declares fields, these can be initialized by defining a constructor and passing arguments to it. The constructor is invoked where the constants are defined.
If an enum type declares fields, these can be initialized by defining a constructor and passing arguments to it. The constructor is invoked where the constants are defined.
toString()
method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.
toString()
method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.
char
value at the specified index. An index ranges from 0
to length() - 1
. The first char
value of the sequence is at index 0
, the next at index 1
, and so on, as for array indexing.
char
value at the specified index. An index ranges from 0
to length() - 1
. The first char
value of the sequence is at index 0
, the next at index 1
, and so on, as for array indexing.
If the char
value specified by the index is a surrogate, the surrogate value is returned.
charAt
in interface CharSequence
index
- the index of the char
value.
char
value at the specified index of this string. The first char
value is at index 0
.
IndexOutOfBoundsException
- if the index
argument is negative or not less than the length of this string.
print(String)
and then println()
.
print(String)
and then println()
.
x
- The String
to be printed.
Examples:
"unhappy".substring(2) returns "happy" "Harbison".substring(3) returns "bison" "emptiness".substring(9) returns "" (an empty string)
beginIndex
- the beginning index, inclusive.
IndexOutOfBoundsException
- if beginIndex
is negative or larger than the length of this String
object.
String
to lower case using the rules of the default locale. This method is equivalent to toLowerCase(Locale.getDefault())
.
String
to lower case using the rules of the default locale. This method is equivalent to toLowerCase(Locale.getDefault())
.
"TITLE".toLowerCase()
in a Turkish locale returns "t\u0131tle"
, where '\u0131' is the LATIN SMALL LETTER DOTLESS I character. To obtain correct results for locale insensitive strings, use toLowerCase(Locale.ROOT)
.
String
, converted to lowercase.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2, 3); String d = cde.substring(1, 2);
The class String
includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character
class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null
argument to a constructor or method in this class will cause a NullPointerException
to be thrown.
A String
represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character
class for more information). Index values refer to char
code units, so a supplementary character uses two positions in a String
.
The String
class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char
values).
Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator
class provides methods for finer-grain, locale-sensitive String comparison.
javac
compiler may implement the operator with StringBuffer
, StringBuilder
, or java.lang.invoke.StringConcatFactory
depending on the JDK version. The implementation of string conversion is typically through the method toString
, defined by Object
and inherited by all classes in Java.
EnumSet
and EnumMap
.
System
class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System
class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
System
class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System
class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Console.charset()
if the Console
exists, stdout.encoding otherwise.
Console.charset()
if the Console
exists, stdout.encoding otherwise.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
See the println
methods in class PrintStream
.
print(String)
and then println()
.
print(String)
and then println()
.
x
- The Object
to be printed.
The locale always used is the one returned by Locale.getDefault(Locale.Category)
with FORMAT
category specified.
format
- A format string
args
- Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java Virtual Machine Specification. The behaviour on a null
argument depends on the conversion.
IllegalFormatException
- If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the formatter class specification.