Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# SCJP5 K&B Octal Literals

Ruwan Scott
Greenhorn

Joined: Jul 14, 2009
Posts: 7
Hi,
question on the following code which appears on Page 177.

out put of this comes as 8 ( integer number). Here the 'eight' is a integer variable. How does it know that 010 is in octal form. why doesn't this variable considers 010 as integer 'Ten'. ( This is not about converting octal 010 to 8. I know how it works). Is there a implicit conversion of anything written as 0s and 1s to Integers ?.

Thanks,
Ruwan
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 17629

33

When a literal starts with zero, the compiler treats the literal as specified in octal.

How does it know that 010 is in octal form.

And there is no such a thing as an "octal form". An int is a value, it doesn't really have a base. It is the compiler that is taking your source of 010, and interpreting it as octal.

Henry

Ruwan Scott
Greenhorn

Joined: Jul 14, 2009
Posts: 7
Henry,
thanks for the explanation.
I need another clarification with following, which is on same page.

this will give the printing output as z = -559035650. Whats the reason to get a minus (-) sign here?

/Ruwan
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 17629

33

Well, this is hexidecimal, which I am assuming you know.

this will give the printing output as z = -559035650. Whats the reason to get a minus (-) sign here?

This requires a bit of explanation... With octal, and with hexidecimal, the compiler allows the number to be specified as an unsigned number. This is because octal and hexidecimal numbers are a common technique to specify bit patterns (such as bit masks). In this case, the number 0xDEADCAFE actually overflows the value of a signed int -- but not an unsigned int. It uses the sign bit as the highest order bit in an unsigned int.

Anyway, to understand how a unsigned number maps to it signed counterpart, you need to userstand "twos-complement".

http://en.wikipedia.org/wiki/Two's_complement

Basically, the very big unsigned number is actually a negative number when the bit patterns are treated as a signed number.

Henry
Ruwan Scott
Greenhorn

Joined: Jul 14, 2009
Posts: 7
Henry,
Thanks. I got it.

/Ruwan

I agree. Here's the link: http://aspose.com/file-tools

subject: SCJP5 K&B Octal Literals