Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Integer — the object wrapper for int

Integer wraps an int value in an object. Learn creation with valueOf, boxing and unboxing, the sum, max, compare, equals and hashCode methods, and why to avoid the Integer(int) constructor.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Integer.valueOf(intValue); Integer.sum(a, b); Integer.max(a, b); Integer.compare(a, b); Integer.hashCode(intValue); boxed.hashCode(); boxed.equals(other);

Integer is the object wrapper for int. Boxing converts int to Integer, while unboxing performs the reverse conversion. A reference can be null; unboxing it throws NullPointerException.

Use Integer.valueOf(int). The Integer(int) constructor, invoked as new Integer(12), is deprecated and marked for removal in Java SE 21. valueOf caches values from -128 through 127 inclusive; it may cache others too.

Integer.sum(a, b) works like a + b; Integer.max(a, b) returns the greater value. Integer.compare(a, b) returns a negative number, zero, or a positive number according to the ordering of its arguments. These methods accept int; arguments of type Integer require unboxing.

Integer.equals(Object) is an instance method: it returns true only for a non-null Integer argument holding the same value. Between Integer references, == compares identity, not value. The instance method hashCode() and static Integer.hashCode(int) return the represented int value.

Examples

public class Main {
    public static void main(String[] args) {
        Integer a = Integer.valueOf(12);
        Integer b = 7;
        System.out.println(Integer.sum(a, b));
        System.out.println(Integer.max(a, b));
        System.out.println(Integer.compare(a, b) > 0);
        System.out.println(a.equals(Integer.valueOf(12)));
        System.out.println(a.hashCode() == Integer.hashCode(12));
    }
}

Result

19
12
true
true
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources