Loading...

Go Back

Next page
Go Back Course Outline

Java Full Course


Java Utility Classes

Essential utility classes for efficient Java programming

Wrapper Classes

Wrapper classes provide a way to use primitive data types as objects. Each primitive type has a corresponding wrapper class.

Byte

byte

Short

short

Integer

int

Long

long

Float

float

Double

double

Character

char

Boolean

boolean

Wrapper Class Usage
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);
    }
}
Output:
Integer value: 100
Double value: 3.14
Character: A
Boolean: true
Parsed int: 123
Parsed double: 3.14159
Integer as string: 100
Double as string: 3.14159
Autoboxing and Unboxing

Autoboxing is the automatic conversion that Java compiler makes between primitive types and their corresponding wrapper classes. Unboxing is the reverse process.

Autoboxing

Primitive → Wrapper

int i = 10;
Integer num = i;

Unboxing

Wrapper → Primitive

Integer num = 10;
int i = num;

Autoboxing and Unboxing Examples
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);
    }
}
Output:
Integer value: 42
Double value: 3.14
Character: J
Boolean: true
Sum of numbers: 60

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.

Math Class

The Math class provides methods for performing basic numeric operations such as exponential, logarithm, square root, and trigonometric functions.

Math Class Examples
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);
    }
}
Output:
Absolute: 15.5
Square root: 5.0
Power: 32.0
Natural log: 4.605170...
Exponential: 7.389056...
Sine: 0.5
Cosine: 0.5
Tangent: 0.999999...
Round: 16
Ceil: 16.0
Floor: 15.0
Min: 15
Max: 25
Random 1: 0.123456...
Random 2: 42
Date and Time (java.time)

The java.time package introduced in Java 8 provides a comprehensive date and time model.

Loading current date and time...
java.time Examples
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);
    }
}
Output:
Current Date: 2023-10-15
Current Time: 14:25:36.123
Current Date-Time: 2023-10-15T14:25:36.123
Current Zoned Date-Time: 2023-10-15T14:25:36.123+02:00[Europe/Paris]
Birthday: 15/06/1990
Meeting Time: 14:30:00
Project Deadline: 31 Dec 2023, 23:59
Meeting Duration: 120 minutes
Age: 33 years
Next Week: 2023-10-22
Previous Month: 2023-09-15
Formatting and Parsing Dates

The DateTimeFormatter class is used for formatting and parsing date-time objects.

Formatting and Parsing Examples
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");
    }
}
Output:
ISO Date: 2023-10-15
ISO Time: 14:25:36.123
Formatted Date: 15 Oct 2023
Formatted Time: 02:25 PM
Formatted Date-Time: Sunday, 15 October 2023 at 02:25 PM
Parsed Date: 1990-06-15
Parsed Time: 14:30:45

Formatting Patterns:
yyyy - Year (2023)
MM - Month (06)
MMM - Month abbreviation (Jun)
MMMM - Full month (June)
dd - Day (15)
EEEE - Full day name (Thursday)
HH - Hour (0-23)
hh - Hour (1-12)
mm - Minute
ss - Second
a - AM/PM
Go Back

Next page