Naveen Kocherla
Naveen Kocherla

Reputation: 499

Clarification about "int" number that begins with 0

public class Test {

    public static void main(String[] args) {
        int i = 012;
        System.out.println(i);
    }
}

Why the output is : 10?

Upvotes: 3

Views: 1356

Answers (4)

Kamlesh Meghwal
Kamlesh Meghwal

Reputation: 4972

Octal Number : Any number start with 0 is considered as an octal number (012) i.e. base-8 number system

Simple octal number evaluation :

1*8^1 + 2*8^0 = 10

Octal Number

For More information about Number System

Upvotes: 3

javawocky
javawocky

Reputation: 919

012 is the octal value for 10 in decimal. So your telling java to print the integer at octal pos 012. Here: http://www.asciitable.com/ shows octal to decimal vaulue conversions.

Upvotes: 2

Maroun
Maroun

Reputation: 95968

See the JLS:

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.

It's a good practice to write:

int i = 0_12;

It might be clearer now, i in decimal is 2*80 + 1*81 = 10.

Upvotes: 7

Constantin
Constantin

Reputation: 8961

If a number starts with 0 it's an octal number with base 8. 012 is in decimal a 10

Upvotes: 14

Related Questions