Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 08 not a valid integer literal in Java?

Tags:

java

int

numbers

Why is 08 considered an out of range int but 07 and below are not?

like image 389
user871303 Avatar asked Aug 28 '11 02:08

user871303


People also ask

Why is 08 or 09 not a valid integer literal in Java?

In most of programming language like Java and C/C++ , the number with leading zero are interpreted as octal number. As we know octal numbers are only represented within 0 to 7 digits only. Hence numbers like 05 , 03 , 054 are valid but the numbers like 078 , 0348 , 09 , 08 are tends to invalid.

What is the value of integer literal 08?

For instance, decimal integer 8 will be written as 010 as octal integer and decimal integer 12 will be written as 014 as octal integer.

Which is not valid int literal?

It has the character u or U at the end of an integer constant. False, It is not an integer constant. Hence the correct answer is 032UU.

Which is a valid integer literal in Java?

There are 4 types of integer literals in Java: binary (base 2) decimal (base 10) octal (base 8)


2 Answers

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

For single-digit numbers (other than 08 and 09, which are not allowed), the result is the same, so you might not notice that they are being interpreted as octal. However, if you write numbers with more than one significant digit you might be confused by the result.

For example:

010 ==  8 024 == 20 

Since octal literals are usually not what you want, you should always take care to never begin an integer literal with 0, unless of course you are actually trying to write zero by itself.

like image 60
Stuart Cook Avatar answered Oct 04 '22 15:10

Stuart Cook


Any number prefixed with a 0 is considered octal. Octal numbers can only use digits 0-7, just like decimal can use 0-9, and binary can use 0-1.

// octal to decimal 01  // 1 02  // 2 07  // 7 010 // 8 020 // 16  // octal to binary (excluding most significant bit) 01  // 1  02  // 10 07  // 111 010 // 1000  020 // 10000 

There are 10 types of people, those who understand ternary, those who don't, and those who think this is a stupid joke.

like image 42
cwallenpoole Avatar answered Oct 04 '22 16:10

cwallenpoole