Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java store Negative numbers in an Integer Variable? [duplicate]

Tags:

java

How does this snippet of code prints "-511" as the output on the console?

   class Test
   {
    public static void main(String[] args) {
    int i = -0777; 
    System.out.printf("%d",i);
    }
   }

Is it to do with the way Java stores Negative numbers?

like image 493
Ashish Krishnan Avatar asked Dec 04 '22 02:12

Ashish Krishnan


2 Answers

Integer numbers prefixed with 0 are octal numbers. To use decimal numbers remove the 0 prefix:

int i = -777;
like image 161
ouah Avatar answered Dec 06 '22 18:12

ouah


Numbers starting with 0 are treated as being in octal by Java. -077 is equivalent to -63, which is what I get when I run your program.

like image 26
Louis Wasserman Avatar answered Dec 06 '22 20:12

Louis Wasserman