简体   繁体   English

为什么不是(123 == 0123)在Java中?

[英]why is not (123 == 0123) in java?

I am developing an application in Android using Eclipse. 我正在使用Eclipse在Android中开发应用程序。 I wrote the following code and in tests the first and third " if " block is not reachable. 我编写了以下代码,并在测试中无法访问第一个和第三个“ if ”块。 Why? 为什么?

When I add a leading zero to a number, the equal operator returns false. 当我在数字前添加零时,等于运算符将返回false。

int var = 123;
if (var == 0123) {
    //not reachable
}
if (var == 123) {
    //reachable
}
if (var == (int)0123) {
    //not reachable
}
if (var == (int)123) {
    //reachable
}

0123 is an octal number ( leading 0 ), while 123 is a decimal number. 0123是八进制数字( 前导0 ),而123是十进制数字。

so 0123 actually equals to 83. 所以0123实际上等于83

Any integer Number Leading With Zero is octal Number (base 8). 以零开头的任何整数都是八进制数(以8为底)。

0123 is octal Number and 123 is Decimal Number 0123是八进制数, 123是十进制数

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

because 0123 in not decimal digit its octal (base 8) so this is equal to 83 因为0123的八进制数(以8为底)不是十进制数字,所以它等于83

To convert a number k to decimal, use the formula that defines its base-8 representation: 要将数字k转换为十进制,请使用定义其以8为底的表示形式的公式:

在此处输入图片说明

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. 八进制数字由一个ASCII数字0和一个或多个ASCII数字0至7组成,可以表示一个正整数,零个整数或负整数。

Note: Octal values are denoted in java by leading zero normal decimal number cannot have a leading zero 注意:在Java中,八进制值由前导零表示,普通十进制数不能有前导零

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM