简体   繁体   English

具有前导零输出的长变量

[英]long variable with leading zero output

I am not able to understand the why such output when long variable with leading zero . 当长变量带有前导零时,我无法理解为什么这样的输出。

public class Test{
        public static void main(String[] args) {
             long var1=00123l;
             long var2=123l;
             System.out.println("Variable 1--->"+var1);
             System.out.println("Variable 2--->"+var2);
             System.out.println(var1==var2);
        }
    }

output: 输出:

Variable 1--->83
Variable 2--->123
false

when a literal is prefixed with 0; 当文字的前缀为0时; java treats it as a octal number. java将其视为八进制数。 When you print that same number, by default it prints in base(10) format. 当您打印相同的数字时,默认情况下它以基本(10)格式打印。 Hence 00123l is printed as 83 . 因此, 00123l被打印为83

The leading zero turns 00123l into an octal literal, and 123 8 =83 10 . 前导零00123l00123l八进制文字,123 8 = 83 10

From the JLS : 来自JLS

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer. 八进制数字由ASCII数字0后跟一个或多个散布有下划线的ASCII数字0到7组成,并且可以表示正整数,零整数或负整数。

When you print the value, it gets printed in base-10, so you see 83 . 当您打印该值时,它将打印在base-10中,因此您会看到83

When you add a leading zero to a value, it is interpreted as an octal value. 向值中添加前导零时,会将其解释为八进制值。

Integers can not store any leading zeros. 整数不能存储任何前导零。 When you need those, store the number as a String. 需要时,将数字存储为字符串。

When you write an integer literal with leading zeroes, it is interpreted as an octal number. 当您使用前导零写入整数文字时,它将被解释为八进制数。 00123 in octal is 83 in decimal. 在八进制中的00123是十进制的83

00123 or 0123 or 0123l all are same for Java. 0012301230123l对于Java都是相同的。 You can test. 你可以测试一下。 They are octal numbers. 它们是八进制数。 If you convert them, you will find (1X8^2)+(1X8^1)(1X8^0)=64+16+3=83 . 如果你转换它们,你会发现(1X8^2)+(1X8^1)(1X8^0)=64+16+3=83 If you want you can store them as String. 如果需要,可以将它们存储为String。

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

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