• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Code Interpretation

 
Atah Tabotnjap
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Java Python Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks man
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
Atah Tabotnjap
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you know what the largest number you can fit into a byte is?
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check the Tutorial on Primitive Data Types, it's all in there.
 
Atah Tabotnjap
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
SO why is it not 127. How does it come to 46 ?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15369
40
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much man. This is very helpful.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49472
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It shows you ought to beware of casting. It doesn’t always do what you expect.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic