Ashwin Upadhyay
Ashwin Upadhyay

Reputation: 151

Why does this output 8?

public class Test {  
    public static void main(String... args) {

        int i=010;

        System.out.print(i);
    }
}

output:

8

Why? What is the logic?

Upvotes: 7

Views: 957

Answers (6)

Bishan
Bishan

Reputation: 15702

In Java and several other languages, an integer literal beginning with 0 is interpreted as an octal (base 8) quantity.

If you write numbers with more than one significant digit you might be confused by the result.

// octal to decimal
01  == 1
02  == 2
07  == 7
010 == 8
020 == 16
024 == 20

// octal to binary (excluding most significant bit)
01  == 1 
02  == 10
07  == 111
010 == 1000 
020 == 10000
024 == 10100

Upvotes: 0

user2389722
user2389722

Reputation:

Using 0 prefix means that you are using octal numbers.

Upvotes: 0

Reimeus
Reimeus

Reputation: 159754

Have a look at the Java Language Specification, Chapter 3.10.1 Integer Literals

An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).

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.

This is why 010 = 8.

Upvotes: 15

JB Nizet
JB Nizet

Reputation: 691695

0 is the prefix for octal numbers, just like 0x is the prefix for hexadecimal numbers (and 0b is the prefix for binary numbers, since Java 7).

So 010 means 1 * 81 + 0 * 80, which is 8.

Upvotes: 27

arjacsoh
arjacsoh

Reputation: 9232

The integer is in octal-System because you have 0 at start.

Upvotes: 2

rocketboy
rocketboy

Reputation: 9741

Because 010, here is octal .

Upvotes: 2

Related Questions