why is not (123 == 0123) in java?
Asked Answered
M

3

25

I am developing an application in Android using Eclipse. I wrote the following code and in tests the first and third "if" block is not reachable. Why?

When I add a leading zero to a number, the equal operator returns false.

int var = 123;
if (var == 0123) {
    //not reachable
}
if (var == 123) {
    //reachable
}
if (var == (int)0123) {
    //not reachable
}
if (var == (int)123) {
    //reachable
}
Magnesite answered 5/5, 2012 at 11:40 Comment(0)
L
55

0123 is an octal number (leading 0), while 123 is a decimal number.

so 0123 actually equals to 83.

Laflam answered 5/5, 2012 at 11:41 Comment(1)
how can i set it as decimal number?Magnesite
B
22

Any integer Number Leading With Zero is octal Number (base 8).

0123 is octal Number and 123 is Decimal Number

 0123 = (3*8^0) +(2*8^1)+(1*8^2)+(0*8^4)
        =3+16+64+0
        =83   
Brumby answered 5/5, 2012 at 11:42 Comment(0)
Z
9

because 0123 in not decimal digit its octal (base 8) so this is equal to 83

To convert a number k to decimal, use the formula that defines its base-8 representation:

enter image description here

0123 base-8 = 83 decimal

0123 = (3*8^0) +(2*8^1)+(1*8^2)+(0*8^4)
     =3+16+64+0
     =83   

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.

Note: Octal values are denoted in java by leading zero normal decimal number cannot have a leading zero

Zendah answered 5/5, 2012 at 11:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.