Convert string to short

In this chapter you will learn:

Decode a string to short value

`Short.decode(String nm)` decodes a String into a Short. It accepts decimal, hexadecimal, and octal numbers given by the following grammar:

``````+/- 0x HexDigits
+/- 0X HexDigits
+/- # HexDigits
+/- 0 OctalDigits
``````

Small demo to illustrates the decode method.

``````public class Main {
public static void main(String[] args) {
/* j a  v  a 2s .co m*/
System.out.println("Decimal 10:"+Short.decode("10"));
System.out.println("Octal 10:"+Short.decode("010"));
System.out.println("Hex F:"+Short.decode("0XF"));

System.out.println("Negative Hex F:"+Short.decode("-0XF"));
}
}
``````

The output:

Convert string to a short value

Short class has the following methods we can use to convert a string to a short type value.

• `static short parseShort(String s)` parses the string argument as a signed decimal short.
• `static short parseShort(String s, int radix)` parses the string argument as a signed short in the radix specified by the second argument.
• `static Short valueOf(short s)` returns a Short instance representing the specified short value.
• `static Short valueOf(String s)` returns a Short object holding the value given by the specified String.
• `static Short valueOf(String s, int radix)` returns a Short object holding the value extracted from the specified String when parsed with the radix given by the second argument.

The following code demonstrates the methods listed above.

``````public class Main {
public static void main(String[] args) {
//from  ja v a 2s.  co m
System.out.println(Short.parseShort("10"));
System.out.println(Short.parseShort("10",8));

System.out.println(Short.valueOf("10"));
System.out.println(Short.valueOf("10",8));

}
}
``````

The output:

Next chapter...

What you will learn in the next chapter:

1. How to reverse the bytes in a short
Home » Java Tutorial » Primitive Data Types