Math and Dates

This lesson covers mathematical operations and date/time handling in Java.

Math Class

The Math class provides common mathematical operation methods, all of which are static.

Common Methods

Method Description Example
abs() Absolute value Math.abs(-5) → 5
max() Maximum Math.max(3, 5) → 5
min() Minimum Math.min(3, 5) → 3
ceil() Round up Math.ceil(3.2) → 4.0
floor() Round down Math.floor(3.8) → 3.0
round() Round to nearest Math.round(3.5) → 4
sqrt() Square root Math.sqrt(16) → 4.0
pow() Power Math.pow(2, 3) → 8.0
random() Random number Math.random() → [0.0, 1.0)

Example: Using Math

JAVA
public class MathDemo {
    public static void main(String[] args) {
        // Absolute value
        System.out.println("abs(-5) = " + Math.abs(-5));  // 5
        
        // Max and min
        System.out.println("max(3, 5) = " + Math.max(3, 5));  // 5
        System.out.println("min(3, 5) = " + Math.min(3, 5));  // 3
        
        // Rounding
        System.out.println("ceil(3.2) = " + Math.ceil(3.2));  // 4.0
        System.out.println("floor(3.8) = " + Math.floor(3.8));  // 3.0
        System.out.println("round(3.5) = " + Math.round(3.5));  // 4
        
        // Power operations
        System.out.println("sqrt(16) = " + Math.sqrt(16));  // 4.0
        System.out.println("pow(2, 3) = " + Math.pow(2, 3));  // 8.0
    }
}
▶ Try it Yourself

Generating Random Numbers

JAVA
public class RandomDemo {
    public static void main(String[] args) {
        // Random number between 0.0 and 1.0
        double r1 = Math.random();
        System.out.println("Random: " + r1);
        
        // Random integer between 1 and 100
        int r2 = (int) (Math.random() * 100) + 1;
        System.out.println("1-100 random: " + r2);
        
        // Random number in range (min to max)
        int min = 10, max = 50;
        int r3 = (int) (Math.random() * (max - min + 1)) + min;
        System.out.println(min + "-" + max + " random: " + r3);
    }
}

Constants

Constant Description Value
Math.PI Pi 3.141592653589793
Math.E Euler's number 2.718281828459045

Example: Calculate Circle Area

JAVA
public class CircleArea {
    public static double area(double radius) {
        return Math.PI * Math.pow(radius, 2);
    }
    
    public static void main(String[] args) {
        double radius = 5;
        System.out.printf("Area of circle with radius %.1f: %.2f%n", radius, area(radius));
        // Area of circle with radius 5.0: 78.54
    }
}
▶ Try it Yourself

Date/Time API (Java 8+)

Java 8 introduced a new date/time API that's easier to use.

LocalDate: Date

JAVA
import java.time.LocalDate;

public class LocalDateDemo {
    public static void main(String[] args) {
        // Today
        LocalDate today = LocalDate.now();
        System.out.println("Today: " + today);  // 2026-06-24
        
        // Specific date
        LocalDate birthday = LocalDate.of(2000, 1, 15);
        System.out.println("Birthday: " + birthday);
        
        // Get fields
        System.out.println("Year: " + today.getYear());
        System.out.println("Month: " + today.getMonthValue());
        System.out.println("Day: " + today.getDayOfMonth());
        System.out.println("Day of week: " + today.getDayOfWeek());
    }
}

LocalTime: Time

JAVA
import java.time.LocalTime;

public class LocalTimeDemo {
    public static void main(String[] args) {
        // Now
        LocalTime now = LocalTime.now();
        System.out.println("Now: " + now);  // 14:30:45.123
        
        // Specific time
        LocalTime meeting = LocalTime.of(14, 30);
        System.out.println("Meeting: " + meeting);
        
        // Get fields
        System.out.println("Hour: " + now.getHour());
        System.out.println("Minute: " + now.getMinute());
        System.out.println("Second: " + now.getSecond());
    }
}

LocalDateTime: Date and Time

JAVA
import java.time.LocalDateTime;

public class LocalDateTimeDemo {
    public static void main(String[] args) {
        // Current date and time
        LocalDateTime now = LocalDateTime.now();
        System.out.println("Now: " + now);
        
        // Specific date and time
        LocalDateTime meeting = LocalDateTime.of(2026, 6, 25, 14, 30);
        System.out.println("Meeting: " + meeting);
    }
}

Date Arithmetic

JAVA
import java.time.LocalDate;

public class DateCalc {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        
        // Add/subtract days
        LocalDate tomorrow = today.plusDays(1);
        LocalDate lastWeek = today.minusWeeks(1);
        LocalDate nextMonth = today.plusMonths(1);
        
        System.out.println("Today: " + today);
        System.out.println("Tomorrow: " + tomorrow);
        System.out.println("Last week: " + lastWeek);
        System.out.println("Next month: " + nextMonth);
        
        // Date comparison
        LocalDate date1 = LocalDate.of(2026, 1, 1);
        LocalDate date2 = LocalDate.of(2026, 12, 31);
        System.out.println("date1 before date2: " + date1.isBefore(date2));
        System.out.println("date1 after date2: " + date1.isAfter(date2));
    }
}

Date Formatting

JAVA
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateFormat {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        
        // Format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formatted = now.format(formatter);
        System.out.println("Formatted: " + formatted);
        
        // Parse
        LocalDateTime parsed = LocalDateTime.parse("2026-06-25 14:30:00", formatter);
        System.out.println("Parsed: " + parsed);
    }
}

Common Format Patterns

Pattern Description Example
yyyy Year 2026
MM Month 06
dd Day 25
HH Hour (24-hour) 14
mm Minute 30
ss Second 45

Example: Calculate Age

JAVA
import java.time.LocalDate;
import java.time.Period;

public class AgeCalculator {
    public static int calculateAge(LocalDate birthday) {
        LocalDate today = LocalDate.now();
        Period period = Period.between(birthday, today);
        return period.getYears();
    }
    
    public static void main(String[] args) {
        LocalDate birthday = LocalDate.of(2000, 1, 15);
        int age = calculateAge(birthday);
        System.out.println("Age: " + age);
    }
}

Example: Calculate Days Between

JAVA
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class DaysBetween {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2026, 1, 1);
        LocalDate end = LocalDate.of(2026, 12, 31);
        
        long days = ChronoUnit.DAYS.between(start, end);
        System.out.println("Days between: " + days);  // 364
    }
}

❓ Frequently Asked Questions

Q What's the range of Math.random()?
A [0.0, 1.0)—includes 0.0 but excludes 1.0.
Q What's the difference between LocalDate and Date?
A LocalDate is Java 8's new API—immutable and thread-safe. Date is the old API—mutable and not thread-safe. LocalDate is recommended.
Q How do I get the current timestamp?
A Use System.currentTimeMillis() for milliseconds, or Instant.now() for an Instant object.

📖 Summary

📝 Exercises

  1. Random numbers: Generate 10 random numbers between 1-100, find the maximum, minimum, and average
  2. Date calculation: Calculate how many days from today to January 1, 2027
  3. Age calculator: Input a birth date and calculate age and days until next birthday

Next Lesson

In the next lesson, we'll learn about Practice: String Processing — applying string-related knowledge.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏