java.lang.Integer decode(String nm)

Description :

This java tutorial shows how to use the decode(String nm) method of Integer class under java.lang package. This method returns a the decoded value into Integer object of the String method argument.

Method Syntax :

public static Integer decode(String nm) throws NumberFormatException

Parameter Input :

DataType Parameter Description
String nm The value that we want to decode into Integer Object

Method Returns :

The decode(String nm) method simply returns the equivalent Integer object interpreted from the String method argument.

Compatibility Version :

Requires Java 1.0 and up

Exception :

NumberFormatException

The NumberFormatException will be thrown by the decode method if and only if the format specified on the method argument is invalid.

Discussion :

The decode(String nm) method is static thus we should invoke it statically for example Integer.decode(String nm). This method simply converts the String parameter to an Integer object. The String accepts octal, hexadecimal and decimal format. This is the same thing as calling the Integer.parseInt(String val, int radix) but only on this case, we are only limited to a certain degree of conversion such as having a radix of 10,8,and 16 only. And also the decode method accepts signed string value.

There is maximum and minimum allowable value to be converted and this is can be determined using the two static method Integer.MAX_VALUE and Integer.MIN_VALUE respectively.

Java Code Example :

This java example source code demonstrates the use of decode(String nm) method of Integer class. Basically we just explored the different possible conversion that can be done using the decode method.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

import static java.lang.System.*;

/*
 * This example source code demonstrates 
 * the use of decode method of Integer class
 */

public class IntegerDecode {

	public static void main(String[] args) {
		// decode the string using base 8
		out.println(Integer.decode("0124"));
		// decode the string using base 16
		out.println(Integer.decode("0x124"));
		// decode the string using base 16 signed
		out.println(Integer.decode("-0x124"));

	}

}

Sample Output :

Running the decode(String nm) method example source code of Integer class will give you the following output

java integer decode method example

java integer decode method example

Exception Scenario :

Exception in thread "main" java.lang.NumberFormatException: For input string: "12GGF"
	at java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at java.lang.Integer.valueOf(Unknown Source)
	at java.lang.Integer.decode(Unknown Source)
	at com.javatutorialhq.java.examples.IntegerDecode.main(IntegerDecode.java:18)

Similar Method :

  • N/A

Suggested Reading List :

References :