tags:

views:

229

answers:

2

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 = Byte.decode("10");

and

Byte b2 = Byte.valueOf("10");
+5  A: 

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.

danben
this gives 'funny' results, like parsing 0-padded values '09'
Salandur
Not so funny if you know that a leading 0 indicates an octal string.
danben
0-padded indicates an octal, as defined by the Java language specification.
Steve Kuo
i know that, but we had problems with a propiarity format, witch was decimal and 0 padded. the xml framework we used while converting used decode, which resulted in errors...
Salandur
@Salandur - that is a bug in the XML framework you are using, or in the way that you are using. The `decode` method is working as specified. You (or the XML framework developers) should not have assumed that `decode` and `valueOf` work the same way.
Stephen C
+2  A: 

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.

jarnbjo