How do I decode string to integer?

The static Integer.decode() method can be use to convert a string
representation of a number into an Integer object. Under the cover
this method call the Integer.valueOf(String s, int radix).

The string can start with the optional negative sign followed with radix specified
such as 0x, 0X, # for hexa decimal value, 0 (zero) for octal number.

package org.kodejava.example.lang;

public class IntegerDecode {
    public static void main(String[] args) {
        String decimal = "10";    // Decimal
        String hexa    = "0XFF";  // Hexa
        String octal   = "077";   // Octal
        
        Integer number = Integer.decode(decimal);
        System.out.println("String [" + decimal + "] = " + number);
        
        number = Integer.decode(hexa);
        System.out.println("String [" + hexa + "] = " + number);
        
        number = Integer.decode(octal);
        System.out.println("String [" + octal + "] = " + number);
    }
}

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply