bhylu.com

Advertisements

Java Choose a Numeric Representation

Choose a numeric type from range and precision requirements. An int count, a long accumulated count and a decimal price do not have the same failure modes.

Understand the idea

Integer arithmetic uses fixed-width types. int covers a smaller range than long, and an ordinary overflowing addition does not automatically throw an exception. float and double represent binary floating-point values, so many decimal fractions are approximations. Use integer minor units or an appropriate BigDecimal policy when exact decimal arithmetic is required. A long literal can use the L suffix to make its intended type clear.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    public static void main(String[] args) {
        long yearlyVisitors = 3_200_000_000L;
        int priceCents = 275;
        int tickets = 4;
        System.out.println(yearlyVisitors);
        System.out.println(priceCents * tickets);
    }
}

Expected output

3200000000
1100

Underscores improve readability inside the numeric literal without changing its value. The price calculation stays in cents, so the output is an exact integer amount. A production money model also needs a currency and an overflow policy; selecting a numeric type alone does not establish those rules.

Check the official Java documentation for detailed contracts and supported options.