简体   繁体   中英

Integer leading zero issue in Java

I wrote a very simple Java program :

class test {
    public static void main (String args[])
    {  
        int i = 23;    
        int j = i/10;   
        System.out.println ("Value of i: " +i);
        System.out.println ("Value of j: " +j);
    }    
}

The output is as expected - i = 23 and j = 2

Now, I kept changing the value of i in the program. And the output started to change.

The value of i = 02 and the output becomes - i = 2 and j = 0

The value of i = 023 and the output becomes - i = 19 and j = 1

Now I am confused. When I gave the value of i = 023 in the program, in the output I expected to get i = 23 and j = 2 . But why is i becoming 19 ?

023 is treated as octal (8) base. 023 in base 8 is 19 in decimal base.

In Java Numbers Starting With 0 treated Octal Numbers ie base 8.

 class Octal{
   public static void main(String[] args){
     int six=06;      //Equal to decimal 6
     int seven=07;    //Equal to decimal 7
     int eight=010;   //Equal to decimal 8
     int nine=011;    //Equal to decimal 9
     System.out.println("Octal 010 :"+eight);
   }
 }

Output is: Octal 010 :8

When you are adding a zero before a number(023), you are actually converting it to octal. And here you are trying to view the output as decimal. So you are getting the decimal equivalent of that input octal.

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