Skip to content

Java Numbers

Java offers primitive data types (byte, int, long, double, float, short, char, boolean) for performance-critical operations. They directly store values.

int i = 5000;
double accountBalance = 13065.75;
byte flags = 0xAF;

However, many Java APIs, especially the Collections Framework, work with objects. To bridge this gap, Java provides wrapper classes for each primitive type (Integer, Long, Byte, Double, Float, Short, Character, Boolean). These classes wrap a primitive value inside an object.

All numeric wrapper classes (Integer, Long, Byte, Double, Float, Short) extend the abstract Number class, providing common methods for number manipulation.

Modern Java simplifies the conversion between primitives and their wrapper objects through autoboxing (primitive to wrapper) and unboxing (wrapper to primitive). The compiler automatically handles these conversions.

Example:

public class TestAutoboxing {
public static void main(String[] args) {
// Autoboxing: int 5 is automatically converted to an Integer object
Integer x = 5;
// Unboxing: Integer x is automatically converted to int for addition
x = x + 10; // x becomes 15 (Integer object)
// Unboxing for printing
System.out.println("Value of x: " + x);
// Example with a List (requires objects)
java.util.List<Integer> numberList = new java.util.ArrayList<>();
numberList.add(100); // Autoboxing: int 100 -> Integer
int firstNum = numberList.get(0); // Unboxing: Integer -> int
System.out.println("First number from list: " + firstNum);
}
}

Output:

Value of x: 15
First number from list: 100
  • NullPointerException: Unboxing a null wrapper reference will throw a NullPointerException. Example: Integer num = null; int i = num; // Throws NPE
  • Performance: Excessive autoboxing/unboxing in performance-sensitive loops can create unnecessary objects and impact performance.
  • Comparison: Use .equals() to compare wrapper object values (Integer a = 1000; Integer b = 1000; a == b might be false, but a.equals(b) is true). == compares object references for objects, but due to caching for small values (-128 to 127), it might appear to work for values in that range.

Instances of wrapper classes (subclasses of Number) provide methods to convert their value to different primitive types, compare them, etc. Static utility methods for parsing and conversion are also available.

CategoryCommon Methods & Description
Instance Methods (on wrapper objects like Integer i = 10;)byte byteValue(), short shortValue(), int intValue(), long longValue(), float floatValue(), double doubleValue(): Convert the Number object’s value to the specified primitive type.
int compareTo(WrapperType another): Compares this Number object to the argument numerically.
boolean equals(Object obj): Compares this Number object to the argument for value equality.
Static Methods (on wrapper classes like Integer.parseInt(...))static WrapperType valueOf(primitive p) or static WrapperType valueOf(String s): Returns a wrapper object representing the specified primitive or String value (often preferred over constructors).
static primitive parsePrimitive(String s) (e.g., parseInt, parseDouble): Parses the string argument as a signed decimal primitive type.
static String toString(primitive p): Returns a String object representing the specified primitive.
Math Utility Methods (Static methods in java.lang.Math and java.lang.StrictMath)abs(a): Returns the absolute value.
ceil(a): Returns the smallest double value that is greater than or equal to the argument and is equal to a mathematical integer.
floor(a): Returns the largest double value that is less than or equal to the argument and is equal to a mathematical integer.
rint(a): Returns the double value that is closest in value to the argument and is equal to a mathematical integer.
round(a): Returns the closest long or int (depending on argument type) to the argument.
min(a, b): Returns the smaller of two values.
max(a, b): Returns the larger of two values.
exp(a): Returns Euler’s number e raised to the power of a double value.
log(a): Returns the natural logarithm (base e) of a double value.
pow(a, b): Returns the value of the first argument raised to the power of the second argument.
sqrt(a): Returns the correctly rounded positive square root of a double value.
sin(a), cos(a), tan(a): Trigonometric functions (angle in radians).
asin(a), acos(a), atan(a): Inverse trigonometric functions.
atan2(y, x): Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta).
toDegrees(a): Converts an angle measured in radians to degrees.
toRadians(a): Converts an angle measured in degrees to radians.
random(): Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

For high-precision arithmetic, especially with financial calculations where floating-point inaccuracies are unacceptable, use the java.math.BigDecimal class.

Next, we’ll explore the Character wrapper class and working with characters in Java.