简体   繁体   中英

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; java treats it as a octal number. When you print that same number, by default it prints in base(10) format. Hence 00123l is printed as 83 .

The leading zero turns 00123l into an octal literal, and 123 8 =83 10 .

From the 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.

When you print the value, it gets printed in base-10, so you see 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 or 0123 or 0123l all are same for 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 . If you want you can store them as String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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