How do I decode string to integer?

The static Integer.decode() method can be used 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 hexadecimal value, 0 (zero) for octal number.

package org.kodejava.lang;

public class IntegerDecode {
    public static void main(String[] args) {
        String decimal = "10"; // Decimal
        String hex = "0XFF"; // Hex
        String octal = "077"; // Octal

        Integer number = Integer.decode(decimal);
        System.out.println("String [" + decimal + "] = " + number);

        number = Integer.decode(hex);
        System.out.println("String [" + hex + "] = " + number);

        number = Integer.decode(octal);
        System.out.println("String [" + octal + "] = " + number);
    }
}

The result of the code snippet above:

String [10] = 10
String [0XFF] = 255
String [077] = 63
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.