I have written some code that used strings to represent time such as "0620", but after careful thought I realised these could be pars开发者_如何学Pythoned into shorts for comparison performance and storage gains.
In a unit test, I have a short written as 0620 being compared against a return value of 620, expecting this to work. However, the test 0620 equals 620 (both are shorts) fails.
The error message says 0620 was interrupted as 400 (and 400 != 620 explaining the failure). Removing the lead 0 fixes the problem, but I wanted to know, what's going on with this?
This doesn't work
assertEquals("Time Failed", 0620, st.GetTime());
This Works
assertEquals("Time Failed", 620, st.GetTime());
An integer literal beginning with a 0
is interpreted as octal (base 8) as per the Java language specification:
An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 and can represent a positive, zero, or negative integer.
I believe this is one of the quirks Java inherited from C.
0620 means octal(base 8) in java I guess it's the same in android or 0620 == 400 not 620
int decVal = 26; // The number 26, in decimal
int octVal = 032; // The number 26, in octal
int hexVal = 0x1a; // The number 26, in hexadecimal
example from java tutorials at SUN/Oracle
精彩评论