How does a leading zero change a numeric literal in Java?

后端 未结 3 1696
名媛妹妹
名媛妹妹 2020-11-29 13:40

My friends and I have puzzled over this statement in Java after seeing it and the answer. How does this work?

System.out.printf(\"%d\", 077);
相关标签:
3条回答
  • 2020-11-29 14:08

    077 is an octal number which equals 7 x 81 + 7 x 80 which is 63 decimal. To display the octal value you could do

    System.out.printf("%o", 077);
    
    0 讨论(0)
  • 2020-11-29 14:17

    When you define an literal integer number with a 0 prefix, the compiler will treat it as an integer base 8. (Octal).

    Check at this post http://rodrigosasaki.com/2013/06/10/number-literals-in-java/

    So, 77 value in Octal base is actually 63 in Decimal base.

    0 讨论(0)
  • 2020-11-29 14:22

    077 = 7 * 8^0 + 7 * 8^1 = 63; 0123 = 3 * 8^0 + 2 * 8^1 + 1 * 8^2 = 3 + 16 + 64 = 83; First 0 means octal value.

    0x77 - is hex val.

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