Java Tutorial » Chapter 13 — Numbers Class

Chapter 13 — Java Numbers Class

Mastering built-in methods for number manipulation and advanced mathematical operations.

1. Introduction

Primitive Types vs. Wrapper Classes

In Java, numbers like int and double are primitive types. They hold values directly in memory. Java also provides wrapper classes (like Integer, Double) that turn these primitives into objects.

This is useful when you need to treat a number as an object, for example, to store it in a list (which can only hold objects) or to use methods that require an object, like those in the Number class. The main wrapper classes are Byte, Short, Integer, Long, Float, and Double.

All numeric wrapper classes inherit from the abstract Number class. The Math class provides many useful static methods that work directly with these wrapper types.

2. Number Methods

Common Methods of the Number Class

Each wrapper class (Integer, Double, etc.) has its own set of useful methods. Here are some of the most important ones.

Java – toString() Method

public class ToStringExample {
    public static void main(String[] args) {
        Integer num = 255;
        String s = num.toString(); // Converts Integer to String
        System.out.println("The string is: " + s);
    }
}

Java – intValue() Method

Returns the value of a number object as an int. This is useful for getting the primitive value back from an object.

public class IntValueExample {
    public static void main(String[] args) {
        Double d = 123.45;
        int i = d.intValue(); // Converts Double to int (truncates)
        System.out.println("The int value is: " + i);
    }
}

Java – valueOf() Method

A static factory method that converts a String or a primitive int into a number object. This is the most common way to create a number object from user input.

public class ValueOfExample {
    public static void main(String[] args) {
        String s = "500";
        Integer i = Integer.valueOf(s); // String to Integer object
        System.out.println("The Integer object is: " + i);
    }
}

Java – equals() Method

Compares this number object to another. Returns true if the values are the same; false otherwise.

public class EqualsExample {
    public static void main(String[] args) {
        Integer num1 = 100;
        Integer num2 = 100;
        
        System.out.println(num1.equals(num2)); // true
        System.out.println(num1.equals(50)); // false
    }
}

Java – compareTo() Method

Compares this number object to another numerically. Returns:

  • A negative integer if this number is less than the other.
  • A positive integer if this number is greater than the other.
  • Zero if the numbers are equal.
public class CompareToExample {
    public static void main(String[] args) {
        Integer a = 10;
        Integer b = 20;
        
        System.out.println(a.compareTo(b)); // Outputs a negative number
        System.out.println(b.compareTo(a)); // Outputs a positive number
    }
}
3. Math Methods

Performing Mathematical Operations

The Math class is full of static methods for common mathematical functions. You don't need to create an object to use them.

Java – abs() Method

Returns the absolute (positive) value of a number. Useful for finding the difference between two numbers without worrying about order.

public class AbsExample {
    public static void main(String[] args) {
        double difference = -50.5;
        System.out.println("Absolute value is: " + Math.abs(difference)); // Prints 50.5
    }
}

Java – ceil() and floor() Methods

ceil() rounds a number up to the nearest integer. floor() rounds a number down to the nearest integer.

public class CeilFloorExample {
    public static void main(String[] args) {
        double a = 3.14;
        System.out.println("Ceiling of 3.14 is: " + Math.ceil(a)); // 4.0
        System.out.println("Floor of 3.14 is: " + Math.floor(a)); // 3.0
    }
}

Java – round() Method

Rounds a double to the nearest integer (long or int) based on standard rounding rules (0.5 rounds up).

public class RoundExample {
    public static void main(String[] args) {
        double a = 3.67;
        System.out.println("Rounded value is: " + Math.round(a)); // 4
    }
}

Java – pow() and sqrt() Methods

pow(base, exponent) raises a number to a power. sqrt(number) returns the square root.

public class PowerRootExample {
    public static void main(String[] args) {
        double base = 2;
        int exp = 3;
        
        double power = Math.pow(base, exp); // 2^3 = 8.0
        double root = Math.sqrt(81);      // sqrt(81) = 9.0
        System.out.println("2 to the power of 3 is: " + power);
        System.out.println("Square root of 81 is: " + root);
    }
}

Java – min() and max() Methods

Finds the minimum or maximum value from a set of numbers.

public class MinMaxExample {
    public static void main(String[] args) {
        int[] numbers = {10, 5, 25, 42, 17};
        
        System.out.println("Min is: " + Math.min(numbers[0], numbers[1])); // 5
        System.out.println("Max is: " + Math.max(numbers[0], numbers[1])); // 42
    }
}

Java – random() Method

Generates a random double between 0.0 (inclusive) and 1.0 (exclusive).

public class RandomExample {
    public static void main(String[] args) {
        // Generates a random double between 0.0 and 1.0
        double randomValue = Math.random(); 
        
        // To get a random integer in a range, you can multiply and cast
        int randomInt = (int)(Math.random() * 100); // Random int from 0 to 99
        System.out.println("Random integer (0-99): " + randomInt);
    }
}
4. Conversion Methods

Converting Between Strings and Numbers

These methods are essential for handling user input, which is often read as a String. The wrapper classes provide methods for this purpose.

Java – parseInt() Method

Parses a string to a signed decimal int. Throws a NumberFormatException if the string is not a valid integer.

public class ParseIntExample {
    public static void main(String[] args) {
        String ageText = "30";
        int age = Integer.parseInt(ageText); // String to int
        System.out.println("Age is: " + age);
    }
}
5. BigInteger

Handling Very Large Numbers

What if you need to work with numbers larger than Long.MAX_VALUE (about 9 quintillion)? The BigInteger class is designed for arbitrary-precision integers.

import java.math.BigInteger;

public class BigIntegerExample {
    public static void main(String[] args) {
        // A number with 100 digits
        String largeNumberString = "12345678901234567890";

        // Create a BigInteger from a string
        BigInteger hugeNumber = new BigInteger(largeNumberString);

        System.out.println("The number is: " + hugeNumber);
        
        // Perform operations
        BigInteger evenLarger = new BigInteger("100000000000000000000000000000000");
        BigInteger result = hugeNumber.add(evenLarger);

        System.out.println("Sum is: " + result);
    }
}

Java – BigDecimal

For financial or scientific calculations where precision is critical, double is not enough. BigDecimal provides perfect control over decimal arithmetic.

import java.math.BigDecimal;

public class BigDecimalExample {
    public static void main(String[] args) {
        // Never use double for money!
        BigDecimal price = new BigDecimal("19.99");
        BigDecimal taxRate = new BigDecimal("0.07");

        // Calculate total with high precision
        BigDecimal total = price.multiply(taxRate.add(BigDecimal.ONE)); // 19.99 * 1.07 = 21.3893

        // Scale to 2 decimal places (standard currency format)
        total = total.setScale(2, RoundingMode.HALF_UP);

        System.out.println("Total price with tax: $" + total);
    }
}
7. Performance Tips

Writing Efficient Code

  • Prefer Primitives: Use int or double over their wrapper classes unless you need an object's features (like being null).
  • Use StringBuilder for String Concatenation: When building a large string in a loop, StringBuilder is much more memory and time-efficient than using the + operator.
  • Caching Expensive Operations: Store the result of a calculation if you need to use it multiple times.
  • Choose the Right Collection: Use ArrayList for random access over LinkedList for sequential access.
8. Practice & Challenge

Test Your Skills

  1. Write a program to convert a temperature from Celsius to Fahrenheit and vice-versa.
  2. Write a program to calculate the area and circumference of a circle given its radius.
  3. Write a program to find the hypotenuse of a right-angled triangle given the other two sides.
  4. Write a program to calculate simple interest (principal, rate, time).
  5. Write a program to generate the first N numbers of the Fibonacci series.
  6. Write a program to check if a number is a palindrome.

🏆 Challenge: High-Precision Calculator

Combine your knowledge of BigInteger and BigDecimal to create a calculator that can handle numbers of any size with perfect precision.

import java.math.BigDecimal;
import java.util.Scanner;

public class PrecisionCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("--- High-Precision Calculator ---");
        System.out.print("Enter first number: ");
        BigDecimal num1 = scanner.nextBigDecimal();
        System.out.print("Enter second number: ");
        BigDecimal num2 = scanner.nextBigDecimal();
        
        // Example operation: Add
        BigDecimal sum = num1.add(num2);
        System.out.println("Sum: " + sum);

        // Example operation: Power
        System.out.print("Enter base: ");
        BigDecimal base = scanner.nextBigDecimal();
        System.out.print("Enter exponent: ");
        int exp = scanner.nextInt();
        BigDecimal power = base.pow(exp);
        System.out.println(base + " to the power of " + exp + " is: " + power);
        
        scanner.close();
    }
}