Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this output 8?

Tags:

java

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

        int i=010;

        System.out.print(i);
    }
}

output:

8

Why? What is the logic?

like image 531
Ashwin Upadhyay Avatar asked Aug 05 '13 17:08

Ashwin Upadhyay


People also ask

Why 010 is 8 in C?

A leading 0 introduces an octal constant, so 010 is octal which is 8 in decimal.

Why 010 is 8?

because java accepts it as an octal value, So 010 = 8.

What is the output of this code >>> Int 3 4?

The answer is 34 (as an integer), first when you add strings they are concatenated so "3" + "4" would give the string "34" then the int() function would change that string into an integer. AL.


2 Answers

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.

like image 144
JB Nizet Avatar answered Oct 02 '22 13:10

JB Nizet


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.

like image 34
Reimeus Avatar answered Oct 02 '22 13:10

Reimeus