Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer leading zero issue in Java

Tags:

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?

like image 299
Man_From_India Avatar asked Mar 28 '26 21:03

Man_From_India


2 Answers

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

like image 65
Eran Avatar answered Apr 01 '26 10:04

Eran


In Java Numbers Starting With 0 treated Octal Numbers i.e. 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

like image 35
AsSiDe Avatar answered Apr 01 '26 11:04

AsSiDe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!