ZetCode

Java Integer Class

Last modified: April 13, 2025

The java.lang.Integer class is a wrapper class for the primitive type int. It provides methods to convert an int to a String and vice versa, as well as other constants and methods useful when working with integers.

The Integer class is part of Java's wrapper classes that encapsulate primitive types. It provides object representation for int values and contains various utility methods for integer manipulation. This class is immutable, meaning its value cannot be changed after creation.

Integer Class Methods

The Integer class provides numerous static and instance methods for working with int values. Key methods include value conversions, string parsing, comparison operations, and bit manipulation utilities. The class also contains useful constants like MIN_VALUE and MAX_VALUE.

public final class Integer extends Number implements Comparable<Integer> {
    public static final int MIN_VALUE = 0x80000000;
    public static final int MAX_VALUE = 0x7fffffff;
    
    public Integer(int value) {...}
    public Integer(String s) throws NumberFormatException {...}
    
    public static int parseInt(String s) throws NumberFormatException {...}
    public static Integer valueOf(int i) {...}
    public static Integer valueOf(String s) throws NumberFormatException {...}
    public static String toString(int i) {...}
    public static String toBinaryString(int i) {...}
    public static String toHexString(int i) {...}
    public static String toOctalString(int i) {...}
    
    public int compareTo(Integer anotherInteger) {...}
    public boolean equals(Object obj) {...}
    public int hashCode() {...}
    public int intValue() {...}
    public String toString() {...}
}

The code above shows the main methods and constants provided by the Integer class. These methods allow for various operations on integer values including conversion, comparison, and string representation.

Creating Integer Objects

Integer objects can be created using constructors or static factory methods. Since Java 9, constructors are deprecated in favor of valueOf() due to better memory management through caching. The class provides two constructors and several valueOf methods.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        // Using constructors (deprecated since Java 9)
        Integer num1 = new Integer(42);
        Integer num2 = new Integer("42");
        
        // Using valueOf() methods (recommended)
        Integer num3 = Integer.valueOf(42);
        Integer num4 = Integer.valueOf("42");
        
        // Autoboxing (automatically uses valueOf internally)
        Integer num5 = 42;
        
        System.out.println("num1: " + num1);
        System.out.println("num2: " + num2);
        System.out.println("num3: " + num3);
        System.out.println("num4: " + num4);
        System.out.println("num5: " + num5);
        
        // Comparing references (demonstrates caching)
        System.out.println("num3 == num4: " + (num3 == num4));
        System.out.println("num3 == num5: " + (num3 == num5));
    }
}

This example demonstrates different ways to create Integer objects. The valueOf() method is preferred as it may return cached objects for values between -128 and 127. The == comparison shows this caching behavior for small integer values.

Parsing Strings to Integers

The Integer class provides several methods to parse strings into integer values. The parseInt() method converts a String to a primitive int, while valueOf() returns an Integer object. Both throw NumberFormatException for invalid input.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        // Parsing decimal strings
        String decimalStr = "12345";
        int primitiveInt = Integer.parseInt(decimalStr);
        Integer objectInt = Integer.valueOf(decimalStr);
        
        // Parsing with different radix (base)
        String binaryStr = "1101";
        int binaryInt = Integer.parseInt(binaryStr, 2);
        
        String hexStr = "FF";
        int hexInt = Integer.parseInt(hexStr, 16);
        
        System.out.println("Decimal parse: " + primitiveInt);
        System.out.println("Decimal valueOf: " + objectInt);
        System.out.println("Binary 1101: " + binaryInt);
        System.out.println("Hex FF: " + hexInt);
        
        try {
            Integer invalid = Integer.valueOf("12a45");
        } catch (NumberFormatException e) {
            System.out.println("Error parsing: " + e.getMessage());
        }
    }
}

This example shows how to parse strings into integers using different number bases. The parseInt() and valueOf() methods can handle various radix values from 2 to 36. The example also demonstrates exception handling for invalid numeric strings.

Converting Integers to Strings

The Integer class provides multiple ways to convert integers to string representations. These include toString() methods for decimal, binary, octal, and hexadecimal formats. Both static and instance methods are available.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        int number = 255;
        Integer numObj = 255;
        
        // Using static toString methods
        System.out.println("Decimal: " + Integer.toString(number));
        System.out.println("Binary: " + Integer.toBinaryString(number));
        System.out.println("Octal: " + Integer.toOctalString(number));
        System.out.println("Hex: " + Integer.toHexString(number));
        
        // Using instance toString method
        System.out.println("Object toString: " + numObj.toString());
        
        // Formatting with leading zeros
        System.out.println("Padded binary: " + 
            String.format("%8s", Integer.toBinaryString(number)).replace(' ', '0'));
        
        // Using toString with radix
        System.out.println("Base 5: " + Integer.toString(number, 5));
    }
}

This example demonstrates various methods to convert integers to strings in different formats. The static toXxxString() methods provide common base conversions, while toString(int i, int radix) allows any base from 2 to 36. The example also shows how to format binary strings with leading zeros.

Comparing Integer Values

Integer objects can be compared using various methods. The compareTo() method compares two Integer objects, while compare() is a static method comparing primitive ints. The equals() method checks value equality for objects.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        Integer a = 10;
        Integer b = 20;
        Integer c = 10;
        int d = 10;
        
        // Using compareTo
        System.out.println("a.compareTo(b): " + a.compareTo(b));
        System.out.println("a.compareTo(c): " + a.compareTo(c));
        
        // Using static compare
        System.out.println("Integer.compare(a, b): " + Integer.compare(a, b));
        System.out.println("Integer.compare(a, c): " + Integer.compare(a, c));
        
        // Using equals
        System.out.println("a.equals(b): " + a.equals(b));
        System.out.println("a.equals(c): " + a.equals(c));
        
        // Comparing with primitive
        System.out.println("a == d: " + (a == d)); // auto-unboxing
    }
}

This example shows different ways to compare integer values. The compareTo() and compare() methods return negative, zero, or positive values indicating ordering. The equals() method checks value equality, while == compares references (except when auto-unboxing occurs with primitives).

Bit Manipulation Methods

The Integer class provides several methods for bit-level operations on integers. These include bit counting, rotation, reversal, and sign manipulation. These methods are useful for low-level programming and performance-sensitive code.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        int number = 0b10101010; // Binary 10101010 (170 decimal)
        
        System.out.println("Original: " + Integer.toBinaryString(number));
        System.out.println("Bit count: " + Integer.bitCount(number));
        System.out.println("Highest one bit: " + 
            Integer.toBinaryString(Integer.highestOneBit(number)));
        System.out.println("Lowest one bit: " + 
            Integer.toBinaryString(Integer.lowestOneBit(number)));
        System.out.println("Number of leading zeros: " + 
            Integer.numberOfLeadingZeros(number));
        System.out.println("Number of trailing zeros: " + 
            Integer.numberOfTrailingZeros(number));
        System.out.println("Reversed bits: " + 
            Integer.toBinaryString(Integer.reverse(number)));
        System.out.println("Rotated left by 2: " + 
            Integer.toBinaryString(Integer.rotateLeft(number, 2)));
    }
}

This example demonstrates various bit manipulation methods available in the Integer class. These methods operate on the binary representation of integers, providing information about bit patterns and enabling bit-level transformations. The results are shown in binary for clarity.

Integer Constants and Size Methods

The Integer class defines several useful constants and size-related methods. These include MIN_VALUE and MAX_VALUE representing the range of int, and SIZE and BYTES representing the size in bits and bytes respectively.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        System.out.println("Integer.MIN_VALUE: " + Integer.MIN_VALUE);
        System.out.println("Integer.MAX_VALUE: " + Integer.MAX_VALUE);
        System.out.println("Integer.SIZE: " + Integer.SIZE + " bits");
        System.out.println("Integer.BYTES: " + Integer.BYTES + " bytes");
        
        // Using size-related methods
        int number = 123456789;
        System.out.println("Signum of " + number + ": " + Integer.signum(number));
        System.out.println("Signum of -" + number + ": " + Integer.signum(-number));
        System.out.println("Signum of 0: " + Integer.signum(0));
        
        // Unsigned operations
        int unsignedCompare = Integer.compareUnsigned(-1, 1);
        System.out.println("Unsigned compare -1 and 1: " + unsignedCompare);
    }
}

This example shows the use of Integer class constants and size-related methods. The MIN_VALUE and MAX_VALUE constants define the range of valid int values. The signum() method returns the sign of a number, while compareUnsigned() performs comparison treating integers as unsigned values.

Source

Java Integer Class Documentation

In this article, we've covered the Java Integer class with practical examples. Understanding these methods is essential for working with integer values in Java, especially when dealing with conversions, parsing, and bit manipulation.

Author

My name is Jan Bodnar, and I am a dedicated programmer with many years of experience in the field. I began writing programming articles in 2007 and have since authored over 1,400 articles and eight e-books. With more than eight years of teaching experience, I am committed to sharing my knowledge and helping others master programming concepts.

List all Java tutorials.