Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are integer literals with leading zeroes interpreted strangely?

Tags:

java

This prints 83

System.out.println(0123) 

However this prints 123

System.out.println(123) 

Why does it work that way?

like image 680
IAdapter Avatar asked Feb 19 '09 14:02

IAdapter


1 Answers

A leading zero denotes that the literal is expressed using octal (a base-8 number).

0123 can be converted by doing (1 * 8 * 8) + (2 * 8) + (3), which equals 83 in decimal. For some reason, octal floats are not available.

Just don't use the leading zero if you don't intend the literal to be expressed in octal.

There is also a 0x prefix which denotes that the literal is expressed in hexadecimal (base 16).

like image 181
luiscubal Avatar answered Oct 09 '22 01:10

luiscubal