9.3 Math & Wrapper Classes
Within the java.lang package, there are reliable assistants designed to help you handle mathematical formulas or perform lightweight data type conversions. Among them, the most widely used are the Math class and the Wrapper classes.
1. The Math Class
This class is heavily packed with useful methods and constants for mathematical calculations.
The biggest defining characteristic of the Math class is that all its members are declared as static. This means you never have to instantiate an object using new Math(). You can conveniently fish them out anytime, anywhere by simply calling Math.methodName().
Useful Math Methods
Math.round(): Rounds the number to the nearest integer and returns along.Math.ceil()/Math.floor(): Rounds the given number up/down and returns adoubletype.Math.max(a, b)/Math.min(a, b): Compares two values and returns the larger/smaller value.Math.random(): Generates a single, truly random floating-point number (a pseudo-random number) between0.0(inclusive) and1.0(exclusive).- (Tip: If you want a random integer value like rolling a dice or drawing lots, you formulate an expression like
(int)(Math.random() * range) + startValueto multiply and truncate the result.)
- (Tip: If you want a random integer value like rolling a dice or drawing lots, you formulate an expression like
public class MathExample {
public static void main(String[] args) {
System.out.println("Rounded: " + Math.round(3.1415)); // 3
System.out.println("Ceiling: " + Math.ceil(3.1415)); // 4.0
System.out.println("Max Value: " + Math.max(100, 200)); // 200
// Rolling a random die from 1 to 6
int dice = (int)(Math.random() * 6) + 1;
System.out.println("Dice Face: " + dice);
}
}
2. Wrapper Classes
Java possesses 8 fundamental primitive data types (like int, char, double, boolean, etc.) that are NOT objects. They are used heavily because they are incredibly lightweight and fast.
However, when engaging deeply with Object-Oriented Programming, the inevitable moment arrives when you must treat these simple numbers or characters exactly like full-fledged Objects(e.g., Collections like ArrayList or Generics can ONLY store Objects, not primitives).
To solve this, Java provides classes that act as a delicate wrapper wrapping around a primitive variable. These are precisely called Wrapper Classes.
Class Matching Table
Generally, you just capitalize the first letter, but int and char have slightly longer names.
byte➔Byteshort➔Shortint➔Integerlong➔Longfloat➔Floatdouble➔Doublechar➔Characterboolean➔Boolean
Boxing & Unboxing
Packing a primitive data type into a Wrapper object is called Boxing, and ripping the package open to extract the primitive from a Wrapper object is called ** Unboxing**.
Since JDK 1.5, the Java compiler graciously handles this packing and unpacking process entirely automatically behind the scenes. This majestic feature is called Auto-boxing and Auto-unboxing. Consequently, you can essentially mix objects and raw numbers indiscriminately, and the computer will calculate them without complaint!
public class WrapperExample {
public static void main(String[] args) {
// [Old Method] "Manual" Boxing yourself
Integer num1 = new Integer(10); // Deprecated! (No longer recommended)
// [Recommended Method] The number 10 is automatically wrapped into an object. (Auto-boxing)
Integer num2 = 10;
// [Auto-unboxing] Mixing an Integer object and a primitive int to add them won't cause an error.
int total = num2 + 20;
System.out.println("Total: " + total); // 30
}
}
The True Weapon of Wrapper Classes (String Conversion/Parsing)
The most frequent and overwhelmingly common reason developers use Wrapper classes is undoubtedly to translate "text characters into real numbers (String Parsing)". When you receive a value from a user, such as from a website input form, Java always perceives it as raw "Text". You need a magic spell to convert it into a legitimate number for calculations.
public class ParsingExample {
public static void main(String[] args) {
String str = "100";
String strDouble = "3.14";
// Converts the string "100" into the real number 100!
int a = Integer.parseInt(str);
// Converts the string "3.14" into the real real-number 3.14!
double b = Double.parseDouble(strDouble);
System.out.println(a + b); // 103.14
}
}
As demonstrated, the java.lang package acts as a formidable cache overflowing with core treasures. It is the enchanted satchel hidden at the very peak of the system containing classes we rely on daily, like the ubiquitous System class (e.g., System.out.println()).
This concludes our foundational expedition into the absolutely essential toolboxes of the Java language. In the next chapter, we will explore immensely critical packages dedicated to controlling Date & Time!