§ 02 — Object-Oriented Programming with Java
This lesson explains how to use Java's built-in classes, constants, imported packages, mathematical methods, and date/time-related 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:
SystemStringMathIntegerDoubleCharacterBooleanA package is a group of related classes. Packages help organize Java's class library.
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 |
04 — Activity: Math Class DemonstrationPro reviewer — not included in this printout.
ProReviewer — locked
Part of this subject's paid reviewers.
Not every Java class is imported automatically. To use classes outside java.lang, you can:
*.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.
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.
Pro2 reviewers locked
Part of this subject's paid reviewers. Not included in this printout.
Experiment with other Math methods like Math.floor(), Math.ceil(), or Math.random().
public class Main {
public static void main(String[] args) {
// Math class
System.out.println("PI: " + Math.PI);
System.out.println("sqrt(144): " + Math.sqrt(144));
System.out.println("pow(2, 10): " + Math.pow(2, 10));
System.out.println("abs(-42): " + Math.abs(-42));
System.out.println("max(18, 21): " + Math.max(18, 21));
// String methods
String s = " Hello, BSIT! ";
System.out.println(s.trim());
System.out.println(s.trim().replace("BSIT", "World"));
// Integer wrapper
System.out.println("Max int: " + Integer.MAX_VALUE);
System.out.println("Parse: " + Integer.parseInt("42"));
}
}Done with this module? Track it — your progress shows on the subject list.
Studying with blockmates? Send them this lesson.
Up next
Lesson 8: GUI Frames and Swing→←Previous: Lesson 6: Constructors and Constructor Overloading