开发者

Byte.decode("10") and Byte.valueOf("10") - what is a difference?

Java 6 API primitive type wrappers have pairs of static methods decode(String s) and valueOf(String s). Both of them return a new object of wrapper class type and none of them are annotated as deprecated. Does someone know the difference between them? For example:

Byte b1 = By开发者_开发问答te.decode("10");

and

Byte b2 = Byte.valueOf("10");


According to the documentation (http://java.sun.com/javase/6/docs/api/java/lang/Byte.html#valueOf%28java.lang.String%29), valueOf only takes Strings that can be interpreted as signed decimal values, while decode takes decimal, hex, or octal Strings (prefixed by 0x, #, or 0) - though valueOf is overloaded to also take the radix explicitly.


The decode method allows you to specify the radix (hex, octal) in the string itself using "0x", "0X" or "#" for hex and "0" as a prefix for octal numbers, while valueOf allows you to pass the radix as a number (e.g. 8 or 16) as an optional parameter. decode("0x10") is equivalent to valueOf("10", 16). Your example valueOf("0x10") will fail with a NumberFormatException.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜