long value with 0 on left

流过昼夜 提交于 2019-11-28 10:02:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!