Man_From_India
Man_From_India

Reputation: 207

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?

Upvotes: 2

Views: 487

Answers (3)

Leo
Leo

Reputation: 5235

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.

Upvotes: 0

AsSiDe
AsSiDe

Reputation: 1846

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

Upvotes: 4

Eran
Eran

Reputation: 393831

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

Upvotes: 6

Related Questions