Java.lang Package Classes

Java Short - decode() Method



The java.lang.Short.decode() method is used to decodes a String into a Short. 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:

  • +
  • -

The sequence of characters following an optional sign and/or radix specifier ("0x", "0X", "#", or leading zero) is parsed as by the Short.parseShort 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.

Syntax

public static Short decode(String nm)
                    throws NumberFormatException

Parameters

No parameter is required.

Return Value

Returns a Short object holding the short value represented by nm.

Exception

Throws NumberFormatException, if the String does not contain a parsable short.

Example:

In the example below, the java.lang.Short.decode() method is used to decode a String into a Short.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating a string holding short value
    String x1 = "25";    //decimal number
    String x2 = "0x6f";  //hexadecimal number
    String x3 = "0X6B";  //hexadecimal number
    String x4 = "-#6c";  //hexadecimal number
    String x5 = "027";   //octal number

    //creating Short object
    Short y1 = Short.decode(x1);
    Short y2 = Short.decode(x2);
    Short y3 = Short.decode(x3);
    Short y4 = Short.decode(x4);
    Short y5 = Short.decode(x5);

    //printing the Short object 
    System.out.println("The Short object y1 is: " + y1);
    System.out.println("The Short object y2 is: " + y2);  
    System.out.println("The Short object y3 is: " + y3);  
    System.out.println("The Short object y4 is: " + y4);  
    System.out.println("The Short object y5 is: " + y5);   
  }
}

The output of the above code will be:

The Short object y1 is: 25
The Short object y2 is: 111
The Short object y3 is: 107
The Short object y4 is: -108
The Short object y5 is: 23

❮ Java.lang - Short