Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Numeric types and arithmetic in Java

Numeric types and arithmetic in Java: Java has integral byte, short, int, long, and char plus floating-point float and double; integer arithmetic wraps at fixed width, while float and double follow IEEE 754.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

numeric types

Java has integral byte, short, int, long, and char plus floating-point float and double; integer arithmetic wraps at fixed width, while float and double follow IEEE 754.

Use int for ordinary counters, long after checking range, BigInteger for unbounded integers, and BigDecimal from a String for decimal money.

Binary numeric promotion usually lifts byte and short to int; integer division discards the remainder, overflow is silent, and new BigDecimal(0.1) preserves the binary approximation.

Integer division by zero throws ArithmeticException, but floating division yields Infinity or NaN; -Integer.MIN_VALUE still equals MIN_VALUE because it overflows.

The output shows overflow=-2147483648, integer-division=0, binary binary-float=0.30000000000000004, exact decimal=0.3, and divide-by-zero=Infinity.

Examples

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        System.out.println("overflow=" + (Integer.MAX_VALUE + 1));
        System.out.println("integer-division=" + (1 / 2));
        System.out.println("binary-float=" + (0.1 + 0.2));
        System.out.println("decimal=" + new BigDecimal("0.1").add(new BigDecimal("0.2")));
        System.out.println("divide-by-zero=" + (1.0 / 0.0));
    }
}

Result

overflow=-2147483648
integer-division=0
binary-float=0.30000000000000004
decimal=0.3
divide-by-zero=Infinity

The output shows overflow=-2147483648, integer-division=0, binary binary-float=0.30000000000000004, exact decimal=0.3, and divide-by-zero=Infinity.

Sources