Working with Enumerations and System Interaction APIs in Java
Enumerations
Overview
An enumeration represents a fixed set of named constants. Defined using the enum keyword, enumerations declare a collection of related constants separated by commas. Common examples include days of the week, calendar months, or cardinal directions.
Declaration
Declare enumerations with the enum keyword, specifying the type name and its members. If no explicit base type is defined, the underlying type defaults to int.
Usage Example
enum Hue {
RED, CYAN, MAGENTA, BLACK;
}
enum Indicator {
GREEN, AMBER, RED
}
class Stoplight {
Indicator signal = Indicator.RED;
void transition() {
switch(signal) {
case RED:
signal = Indicator.GREEN;
break;
case AMBER:
signal = Indicator.RED;
break;
case GREEN:
signal = Indicator.AMBER;
break;
}
}
}
Enum Class Internals
Each enumeration implicit extends java.lang.Enum. Members are treated as static final instances of the enum type. Key inherited methods include:
values(): Returns all enum constants as an arrayvalueOf(String): Converts a string to the corresponding enum constantcompareTo(E): Compares declaration order of two constantsordinal(): Returns the zero-based postiion of the constant
Method Demonstrations
Iterating through constants:
enum Status { ACTIVE, INACTIVE, PENDING }
class Processor {
public static void main(String[] args) {
for (Status s : Status.values()) {
System.out.println("Constant: " + s);
}
}
}
Comparing constants:
enum Category { PRIMARY, SECONDARY }
class Comparator {
static void evaluate(Category c) {
for (Category ref : Category.values()) {
System.out.println(c + " vs " + ref + ": " + c.compareTo(ref));
}
}
}
Getting declartaion indices:
enum Priority { HIGH, MEDIUM, LOW }
class Indexer {
public static void main(String[] args) {
for (Priority p : Priority.values()) {
System.out.println(p.ordinal() + ": " + p);
}
}
}
Adding Functionality to Enums
Enums can contain constructors, fields, and methods. Constants must be declared before any additional members.
enum Day {
MON("Monday"), TUE("Tuesday"), WED("Wednesday"),
THU("Thursday"), FRI("Friday"), SAT("Saturday"), SUN("Sunday");
private final String fullName;
Day(String name) {
this.fullName = name;
}
String getFullName() {
return fullName;
}
static void display(int num) {
switch(num) {
case 1 -> System.out.println(MON);
case 2 -> System.out.println(TUE);
// Additional cases omitted for brevity
}
}
}
Specialized Collections
- EnumMap: Optimized map implementation for enum keys
- EnumSet: High-performance set for enum constants
System Interaction Classes
Console Operations
The Console class facilitates character-based console interactions.
import java.io.Console;
class ConsoleHandler {
public static void main(String[] args) {
Console terminal = System.console();
if (terminal != null) {
String username = terminal.readLine("Username: ");
char[] password = terminal.readPassword("Password: ");
terminal.printf("Authenticated: %s%n", username);
}
}
}
Input Processing with Scanner
The Scanner class parses primitive types and strings from input sources.
Token vs Line Input
import java.util.Scanner;
class InputDemo {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Token input: ");
if (reader.hasNext()) {
String token = reader.next();
System.out.println("Received: " + token);
}
System.out.print("Line input: ");
if (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println("Received: " + line);
}
reader.close();
}
}
Type-Specific Parsing
import java.util.Scanner;
class DataReader {
public static void main(String[] args) {
Scanner parser = new Scanner(System.in);
String name = parser.nextLine();
int age = parser.nextInt();
double balance = parser.nextDouble();
parser.close();
System.out.printf("Name: %s, Age: %d, Balance: %.2f%n", name, age, balance);
}
}
Aggregation Example
import java.util.Scanner;
class StatisticsCalculator {
public static void main(String[] args) {
Scanner collector = new Scanner(System.in);
double total = 0;
int count = 0;
while (collector.hasNextDouble()) {
total += collector.nextDouble();
count++;
}
System.out.printf("%d values | Sum: %.2f | Average: %.2f%n",
count, total, total/count);
collector.close();
}
}
System Utilities
Core System Class
The System class provides access to system resources and environment properties.
Array Manipulation
class ArrayUtils {
public static void main(String[] args) {
char[] source = {'X', 'Y', 'Z', 'W'};
char[] target = {'A', 'B', 'C', 'D'};
System.arraycopy(source, 1, target, 2, 2);
// Result: target becomes ['A', 'B', 'Y', 'Z']
}
}
Performance Measurement
class Benchmark {
public static void main(String[] args) {
long start = System.currentTimeMillis();
// Operation to measure
long duration = System.currentTimeMillis() - start;
System.out.println("Execution time: " + duration + "ms");
}
}
Environment Properties
class EnvironmentInspector {
public static void main(String[] args) {
System.out.println("Java Version: " + System.getProperty("java.version"));
System.out.println("OS Name: " + System.getProperty("os.name"));
System.out.println("User Home: " + System.getProperty("user.home"));
}
}
Process Control
class ProcessManager {
public static void terminate(int statusCode) {
System.exit(statusCode);
}
public static void requestCleanup() {
System.gc();
}
}