Lesson Overview
This lesson explains how to use Java's built-in classes, constants, imported packages, mathematical methods, and date/time-related classes.
Automatically Available Classes
Java provides many ready-made classes. Some are available automatically because every Java program imports the java.lang package by default.
Examples of commonly used classes from java.lang include:
SystemStringMathIntegerDoubleCharacterBoolean
A package is a group of related classes. Packages help organize Java's class library.
Math Constants and Methods
The Math class provides useful constants and methods for numeric calculations. Its members are static, so they are called using the class name.
Math.PI
Math.sqrt(25)
Math.max(5, 3)
Common Math members:
| Member | Purpose |
|---|---|
Math.PI | Value of pi |
Math.abs(x) | Absolute value |
Math.sqrt(x) | Square root |
Math.pow(x, y) | x raised to the y power |
Math.round(x) | Nearest whole number |
Math.ceil(x) | Smallest whole number not less than x |
Math.floor(x) | Largest whole number not greater than x |
Math.max(x, y) | Larger of two values |
Math.min(x, y) | Smaller of two values |
Math.sin(x) | Sine, using radians |
Math.cos(x) | Cosine, using radians |
Math.random() | Random decimal from 0.0 up to but not including 1.0 |
Activity: Math Class Demonstration
Importing Prewritten Classes
Not every Java class is imported automatically. To use classes outside java.lang, you can:
- Use the full package path.
- Import a specific class.
- Import all classes from a package using
*.
Examples:
java.util.Date today = new java.util.Date();
import java.util.Date;
Date today = new Date();
import java.util.*;
Date today = new Date();
Import statements are placed before the class declaration.
Date and Time Classes
Older Java programs may use java.util.Date, but many of its methods are now considered legacy. For modern Java, prefer the java.time package, such as LocalDate and LocalDateTime.
Activity: Modern Date Example
Laboratory Exercises
Try It: Prewritten Classes
Experiment with other Math methods like Math.floor(), Math.ceil(), or Math.random().