long value with 0 on left

后端 未结 5 845
星月不相逢
星月不相逢 2020-12-21 16:47

Why this behavior happens?

long value = 123450;
System.out.println(\"value: \" + value); 

value: 123450

 

long         


        
相关标签:
5条回答
  • 2020-12-21 16:53

    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

    0 讨论(0)
  • 2020-12-21 16:58

    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.

    0 讨论(0)
  • 2020-12-21 17:00

    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.

    0 讨论(0)
  • 2020-12-21 17:00

    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)); 
    
    0 讨论(0)
  • 2020-12-21 17:09

    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.

    0 讨论(0)
提交回复
热议问题