Essential utility classes for efficient Java programming
Wrapper classes provide a way to use primitive data types as objects. Each primitive type has a corresponding wrapper class.
byte
short
int
long
float
double
char
boolean
public class WrapperDemo {
public static void main(String[] args) {
// Creating wrapper objects
Integer num1 = Integer.valueOf(100);
Double num2 = Double.valueOf(3.14);
Character letter = Character.valueOf('A');
Boolean flag = Boolean.valueOf(true);
// Converting to primitive
int intValue = num1.intValue();
double doubleValue = num2.doubleValue();
char charValue = letter.charValue();
boolean boolValue = flag.booleanValue();
// Parsing strings
int parsedInt = Integer.parseInt("123");
double parsedDouble = Double.parseDouble("3.14159");
// Converting to string
String intStr = num1.toString();
String doubleStr = Double.toString(3.14159);
// Displaying results
System.out.println("Integer value: " + intValue);
System.out.println("Double value: " + doubleValue);
System.out.println("Character: " + charValue);
System.out.println("Boolean: " + boolValue);
System.out.println("Parsed int: " + parsedInt);
System.out.println("Parsed double: " + parsedDouble);
System.out.println("Integer as string: " + intStr);
System.out.println("Double as string: " + doubleStr);
}
}
Autoboxing is the automatic conversion that Java compiler makes between primitive types and their corresponding wrapper classes. Unboxing is the reverse process.
Primitive → Wrapper
int i = 10;
Integer num = i;
Wrapper → Primitive
Integer num = 10;
int i = num;
import java.util.ArrayList;
public class AutoBoxingDemo {
public static void main(String[] args) {
// Autoboxing examples
Integer num1 = 42; // primitive int to Integer
Double num2 = 3.14; // primitive double to Double
Character letter = 'J'; // primitive char to Character
Boolean flag = true; // primitive boolean to Boolean
// Unboxing examples
int intValue = num1; // Integer to primitive int
double doubleValue = num2; // Double to primitive double
char charValue = letter; // Character to primitive char
boolean boolValue = flag; // Boolean to primitive boolean
// Autoboxing in collections
ArrayList numbers = new ArrayList<>();
numbers.add(10); // Autoboxing: int to Integer
numbers.add(20);
numbers.add(30);
// Unboxing from collections
int sum = 0;
for (Integer n : numbers) {
sum += n; // Unboxing: Integer to int
}
// Display results
System.out.println("Integer value: " + intValue);
System.out.println("Double value: " + doubleValue);
System.out.println("Character: " + charValue);
System.out.println("Boolean: " + boolValue);
System.out.println("Sum of numbers: " + sum);
}
}
Performance Note: While autoboxing and unboxing are convenient, they can have performance implications in performance-critical applications due to the creation of objects. Use primitives when possible for better performance.
The Math class provides methods for performing basic numeric operations such as exponential, logarithm, square root, and trigonometric functions.
public class MathDemo {
public static void main(String[] args) {
// Basic operations
double absValue = Math.abs(-15.5);
double sqrtValue = Math.sqrt(25);
double powValue = Math.pow(2, 5);
double logValue = Math.log(100);
double expValue = Math.exp(2);
// Trigonometric functions
double sinValue = Math.sin(Math.PI / 6);
double cosValue = Math.cos(Math.PI / 3);
double tanValue = Math.tan(Math.PI / 4);
// Rounding
long roundValue = Math.round(15.75);
double ceilValue = Math.ceil(15.25);
double floorValue = Math.floor(15.75);
// Min and max
int minValue = Math.min(15, 25);
int maxValue = Math.max(15, 25);
// Random numbers
double random1 = Math.random();
int random2 = (int)(Math.random() * 100); // Random between 0-99
// Display results
System.out.println("Absolute: " + absValue);
System.out.println("Square root: " + sqrtValue);
System.out.println("Power: " + powValue);
System.out.println("Natural log: " + logValue);
System.out.println("Exponential: " + expValue);
System.out.println("Sine: " + sinValue);
System.out.println("Cosine: " + cosValue);
System.out.println("Tangent: " + tanValue);
System.out.println("Round: " + roundValue);
System.out.println("Ceil: " + ceilValue);
System.out.println("Floor: " + floorValue);
System.out.println("Min: " + minValue);
System.out.println("Max: " + maxValue);
System.out.println("Random 1: " + random1);
System.out.println("Random 2: " + random2);
}
}
The java.time package introduced in Java 8 provides a comprehensive date and time model.
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class DateTimeDemo {
public static void main(String[] args) {
// Current date and time
LocalDate currentDate = LocalDate.now();
LocalTime currentTime = LocalTime.now();
LocalDateTime currentDateTime = LocalDateTime.now();
ZonedDateTime currentZonedDateTime = ZonedDateTime.now();
// Specific date and time
LocalDate birthday = LocalDate.of(1990, Month.JUNE, 15);
LocalTime meetingTime = LocalTime.of(14, 30);
LocalDateTime projectDeadline = LocalDateTime.of(2023, 12, 31, 23, 59);
// Duration and Period
Duration duration = Duration.between(meetingTime, meetingTime.plusHours(2));
Period period = Period.between(birthday, currentDate);
// Formatting
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm");
// Calculations
LocalDate nextWeek = currentDate.plus(1, ChronoUnit.WEEKS);
LocalDate previousMonth = currentDate.minus(1, ChronoUnit.MONTHS);
// Display results
System.out.println("Current Date: " + currentDate);
System.out.println("Current Time: " + currentTime);
System.out.println("Current Date-Time: " + currentDateTime);
System.out.println("Current Zoned Date-Time: " + currentZonedDateTime);
System.out.println("Birthday: " + birthday.format(dateFormatter));
System.out.println("Meeting Time: " + meetingTime.format(timeFormatter));
System.out.println("Project Deadline: " + projectDeadline.format(dateTimeFormatter));
System.out.println("Meeting Duration: " + duration.toMinutes() + " minutes");
System.out.println("Age: " + period.getYears() + " years");
System.out.println("Next Week: " + nextWeek);
System.out.println("Previous Month: " + previousMonth);
}
}
The DateTimeFormatter class is used for formatting and parsing date-time objects.
import java.time.*;
import java.time.format.*;
public class DateFormatting {
public static void main(String[] args) {
// Current date and time
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
// Predefined formatters
DateTimeFormatter isoDate = DateTimeFormatter.ISO_LOCAL_DATE;
DateTimeFormatter isoTime = DateTimeFormatter.ISO_LOCAL_TIME;
// Custom formatters
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy");
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("EEEE, dd MMMM yyyy 'at' hh:mm a");
// Formatting dates
String formattedDate = date.format(dateFormatter);
String formattedTime = time.format(timeFormatter);
String formattedDateTime = dateTime.format(dateTimeFormatter);
// Parsing dates
LocalDate parsedDate = LocalDate.parse("15-06-1990", DateTimeFormatter.ofPattern("dd-MM-yyyy"));
LocalTime parsedTime = LocalTime.parse("14:30:45", DateTimeFormatter.ofPattern("HH:mm:ss"));
// Display results
System.out.println("ISO Date: " + date.format(isoDate));
System.out.println("ISO Time: " + time.format(isoTime));
System.out.println("Formatted Date: " + formattedDate);
System.out.println("Formatted Time: " + formattedTime);
System.out.println("Formatted Date-Time: " + formattedDateTime);
System.out.println("Parsed Date: " + parsedDate);
System.out.println("Parsed Time: " + parsedTime);
// Formatting patterns cheat sheet
System.out.println("\nFormatting Patterns:");
System.out.println("yyyy - Year (2023)");
System.out.println("MM - Month (06)");
System.out.println("MMM - Month abbreviation (Jun)");
System.out.println("MMMM - Full month (June)");
System.out.println("dd - Day (15)");
System.out.println("EEEE - Full day name (Thursday)");
System.out.println("HH - Hour (0-23)");
System.out.println("hh - Hour (1-12)");
System.out.println("mm - Minute");
System.out.println("ss - Second");
System.out.println("a - AM/PM");
}
}