java.lang.Byte decode(String nm)

Description

The decode(String nm) method of Byte class is used to decode a String into a Byte. Accepts decimal, hexadecimal, and octal numbers given by the following grammar:

DecodableString:
Signopt DecimalNumeral
Signopt 0x HexDigits
Signopt 0X HexDigits
Signopt # HexDigits
Signopt 0 OctalDigits

Sign:

+

DecimalNumeral, HexDigits, and OctalDigits are as defined in section 3.10.1 of The Java™ Language Specification, except that underscores are not accepted between digits.

The sequence of characters following an optional sign and/or radix specifier (“0x”, “0X”, “#”, or leading zero) is parsed as by the Byte.parseByte method with the indicated radix (10, 16, or 8). This sequence of characters must represent a positive value or a NumberFormatException will be thrown. The result is negated if first character of the specified String is the minus sign. No whitespace characters are permitted in the String.

Important Notes:

  • The method decode(String nm) throws a NumberFormatException, if the String does not contain a parsable byte.

Method Syntax

public static Byte decode(String nm)
throws NumberFormatException

Method Argument

Data Type Parameter Description
String nm the String to decode.

Method Returns

The decode(String nm) method of Byte class returns a Byte object holding the byte value represented by nm.

Compatibility

Requires Java 1.1 and up

Java Byte decode(String nm) Example

Below is a simple java example on the usage of decode(String nm) method of Byte class.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

/*
 * This example source code demonstrates the use of 
 * decode(String nm) method of Byte class.
 */

public class ByteDecodeExample {

	public static void main(String[] args) {

		// ask for user input
		System.out.print("Enter a value:");

		// read the user input
		Scanner s = new Scanner(System.in);
		String value = s.nextLine();
		s.close();

		// decode the user input into byte
		Byte result = Byte.decode(value);

		// print the result
		System.out.print("Decoded value is " + result);

	}

}

Basically on the above example, users were asked to enter a value to be decoded. The decoded value were displayed on the console.

Sample Output

Below is the sample output when you run the above example.

java Byte decode() example output