Java Topic
Java Enums
Enums (short for enumerations) in Java are a special type of class that represent a group of constants (unchangeable variables, like final variables). Enums are used to define a set of named values and are a great way to define and use a fixed set of constants in your code.
1. Defining an Enum
Enums are defined using the enum keyword. Here’s how you can define a simple enum:
public enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
This Day enum represents the days of the week.
2. Using Enums
Enums can be used in switch statements, for comparisons, or just for holding a set of constants:
public class Main {
public static void main(String[] args) {
Day today = Day.FRIDAY;
switch (today) {
case Day.MONDAY:
System.out.println("Start of work week");
break;
case Day.FRIDAY:
System.out.println("End of work week");
break;
default:
System.out.println("Midweek");
break;
}
}
}
In this example, the switch statement uses the Day enum to determine the day of the week and print a corresponding message.
3. Enum Methods
Enums have some built-in methods that can be useful:
name(): Returns the name of the enum constant.ordinal(): Returns the position of the enum constant in its enum declaration.values(): Returns an array of all the enum constants.valueOf(String name): Returns the enum constant with the specified name.
public class EnumExample {
public static void main(String[] args) {
Day day = Day.WEDNESDAY;
System.out.println(day.name()); // Outputs "WEDNESDAY"
System.out.println(day.ordinal()); // Outputs 3
for (Day d : Day.values()) {
System.out.println(d);
}
}
}
This example demonstrates the usage of name(), ordinal(), and values() methods of enums.
4. Enum with Fields and Methods
Enums can have fields, methods, and constructors. Each enum constant can have different values for these fields:
public enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.378e6),
MARS(6.421e+23, 3.397e6);
private final double mass; // in kilograms
private final double radius; // in meters
private Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() {
return mass;
}
public double radius() {
return radius;
}
public double surfaceGravity() {
final double G = 6.67300E-11; // gravitational constant
return G * mass / (radius * radius);
}
}
In this example, the Planet enum has fields for mass and radius, and methods to calculate surface gravity.
5. Enum in Switch Statements
Enums are often used in switch statements to execute different code based on the enum value:
public class TrafficLight {
public enum Light {
RED,
YELLOW,
GREEN
}
public void printAction(Light light) {
switch (light) {
case Light.RED:
System.out.println("Stop");
break;
case Light.YELLOW:
System.out.println("Caution");
break;
case Light.GREEN:
System.out.println("Go");
break;
}
}
public static void main(String[] args) {
TrafficLight tl = new TrafficLight();
tl.printAction(Light.GREEN);
}
}
This example uses the TrafficLight class to handle different traffic light actions using a switch statement.
Java Date and Time
Handling date and time in Java has evolved significantly. The traditional java.util.Date and java.util.Calendar classes were replaced by the more modern and flexible java.time package introduced in Java 8. The new date and time API offers more accurate and comprehensive ways to manage date and time.
1. Using java.util.Date
The Date class is a simple class that represents a specific instant in time, with millisecond precision.
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
Date now = new Date();
System.out.println("Current date and time: " + now);
}
}
Note that Date has been largely supplanted by the java.time package.
2. Using java.util.Calendar
Calendar provides a way to manipulate dates and times with more precision than Date alone.
import java.util.Calendar;
public class CalendarExample {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("Current date and time: " + calendar.getTime());
calendar.add(Calendar.MONTH, 1);
System.out.println("Date after one month: " + calendar.getTime());
}
}
This example shows how to get the current date and time and add a month to it using Calendar.
3. Using java.time Package
The java.time package provides a more comprehensive and consistent API for date and time manipulation.
LocalDate
LocalDate represents a date without time-zone.
import java.time.LocalDate;
public class LocalDateExample {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
LocalDate futureDate = today.plusDays(30);
System.out.println("Date after 30 days: " + futureDate);
}
}
In this example, LocalDate.now() provides the current date, and plusDays() adds 30 days to it.
LocalTime
LocalTime represents a time without date or time-zone.
import java.time.LocalTime;
public class LocalTimeExample {
public static void main(String[] args) {
LocalTime now = LocalTime.now();
System.out.println("Current time: " + now);
LocalTime futureTime = now.plusHours(2);
System.out.println("Time after 2 hours: " + futureTime);
}
}
This example shows how to get the current time and add 2 hours to it using LocalTime.
LocalDateTime
LocalDateTime combines date and time without time-zone.
import java.time.LocalDateTime;
public class LocalDateTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("Current date and time: " + now);
LocalDateTime futureDateTime = now.plusWeeks(1);
System.out.println("Date and time after 1 week: " + futureDateTime);
}
}
Here, LocalDateTime.now() returns the current date and time, and plusWeeks() adds one week to it.
ZonedDateTime
ZonedDateTime represents a date and time with a time-zone.
import java.time.ZonedDateTime;
import java.time.ZoneId;
public class ZonedDateTimeExample {
public static void main(String[] args) {
ZonedDateTime now = ZonedDateTime.now();
System.out.println("Current date and time with time-zone: " + now);
ZonedDateTime futureDateTime = now.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println("Date and time in New York: " + futureDateTime);
}
}
This example shows how to get the current date and time with time-zone information and convert it to a different time-zone using ZonedDateTime.
4. Formatting and Parsing
To format and parse dates and times, use the DateTimeFormatter class.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterExample {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate date = LocalDate.now();
String formattedDate = date.format(formatter);
System.out.println("Formatted date: " + formattedDate);
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
System.out.println("Parsed date: " + parsedDate);
}
}
This example demonstrates formatting a LocalDate to a string and then parsing it back to a LocalDate using DateTimeFormatter.
Comments (0)
No comments yet. Be the first to comment!