问题
Why this behavior happens?
long value = 123450;
System.out.println("value: " + value);
value: 123450
long value = 0123450;
// ^
System.out.println("value: " + value);
value: 42792
What is this 42792?
回答1:
Why this behavior happens?
Just as literals starting with 0x
are treated as hexadecimal numbers (base 16), literals starting with a 0
are treated as octal numbers, i.e., numbers in base 8.
(Try writing 0789, and you'll see that the compiler will complain.)
What is this 42792?
The number 123450 in base 8 represents the number
1×85 + 2×84 + 3×83 + 4×82 + 5×81 + 0×80 = 42792
回答2:
If you prefix a number with a zero, it is understood to be octal (base 8). However, println writes it in base 10.
123450 octal = 42792 decimal.
回答3:
That's the way java represent an octal literal. Take a look at this:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
If what you want is to print something with zeros in the left you need to use DecimalFormat format method.
http://download.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
In that case you do this:
long value = 123450;
DecimalFormat df = new DecimalFormat("0");
System.out.println("value: " + df.format(value));
回答4:
Octal literal. See Java Language Specification, 3.10.1 for detailed, albeit somewhat dry, description of Java number literals. To find and study more fun stuff like that, refer to 'Java puzzlers' book.
回答5:
This feature dates back to the early 'C' days. A leading '0' is for octal, a leading '0x' is for hexidecimal. It has been proposed that '0b' be for binary numbers for JDK 7.
You can parse such a number with Integer.decode(String)
which also accepts a leading '#' as a hexi-decimal number.
来源:https://stackoverflow.com/questions/5540179/long-value-with-0-on-left