Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# Code Interpretation

Atah Tabotnjap
Greenhorn
Posts: 24
Can someone please help explain the outcome of this piece of code ?

int x = 010;
double y = 2.5;
double erg = x + y;
x++;
System.out.println("x is " + x);
System.out.println("y is " + y);
System.out.println("erg is " + erg);

After running it, the outcome is :
x is 9
y is 2.5
erg is 10.5

Why is it not :
x is 11
y is 2.5
erg is 12.5

Thanks !

Kemal Sokolovic
Bartender
Posts: 825
5
• 1
An integer preceded with zero is interpreted as octal number, so decimal value of x after initialization is 8.

Edit: And please UseCodeTags when posting source code.

Atah Tabotnjap
Greenhorn
Posts: 24
Thanks man

Kemal Sokolovic
Bartender
Posts: 825
5
You're welcome.

Atah Tabotnjap
Greenhorn
Posts: 24
Hi Kemal,

maybe you can help me interprete this one as well:

The outcome is:
exactNUmber is 1582.769230769231
wholeNumber is 1582
overFlow is 46

i do not understand how the INT 1582 becomes 46 when casted to BYTE.

Thanks a lot in advance.

Matthew Brown
Bartender
Posts: 4567
8
Do you know what the largest number you can fit into a byte is?

Kemal Sokolovic
Bartender
Posts: 825
5
Check the Tutorial on Primitive Data Types, it's all in there.

Atah Tabotnjap
Greenhorn
Posts: 24
SO why is it not 127. How does it come to 46 ?

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15286
39
• 1
Because casting an int to byte simply cuts off bits 31-8, leaving bits 7-0 in the byte.

1582 in binary (32 bits) is: 0000 0000 0000 0000 0000 0110 0010 1110

The last 8 bits are: 0010 1110 which is 46 in decimal.

Atah Tabotnjap
Greenhorn
Posts: 24
Thank you very much man. This is very helpful.

Campbell Ritchie
Sheriff
Posts: 48976
60
It shows you ought to beware of casting. It doesn’t always do what you expect.