How to convert String to Integer in Java?

UPDATED: 18 July 2015
Integer.parseInt(String s)
You can convert any String that represents number into signed decimal integer by passing String as an argument to method Integer.parseInt(String s). Following excerpt shows how you can convert String to Integer in Java.
public class StringToInteger {
    public static void main(String[] args) {
        String strNumber = "123";
        System.out.println("Number in String: " + strNumber);
        
        /**
         * javadoc:
         * Parses the string argument as a signed decimal integer. 
         * The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. 
         * The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the Integer.parseInt(java.lang.String, int) method.
         * 
         * Throws: NumberFormatException - if the string cannot be parsed as an integer. 
         */
        int intValue = Integer.parseInt(strNumber);
        System.out.println("int value: " + intValue);
        
        /* Increment value by 1 */
        intValue = intValue + 1;
        System.out.println("int value incremented: " + intValue);
    }
}

Output
Number in String: 123
int value: 123
int value increment: 124

Radix
Following table represent the numbering system in mathematics. Read more about it on wikipedia.
Base/Radix Name
10 Decimal system
12 DuoDecimal(dozenal) system
2 Binary numeral system
16 HexaDecimal system
8 Octal system
60 Sexagesimal system
64 MIME Base64
85 PostScript ASCII85
256 byte


0 comments :