Get your CodeRanch badge!*
The moose likes Beginning Java and the fly likes Code Interpretation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Code Interpretation" Watch "Code Interpretation" New topic
Author

Code Interpretation

Atah Tabotnjap
Greenhorn

Joined: Mar 17, 2008
Posts: 21
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

Joined: Jun 19, 2010
Posts: 825
    
    5

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.


The quieter you are, the more you are able to hear.
Atah Tabotnjap
Greenhorn

Joined: Mar 17, 2008
Posts: 21
Thanks man
Kemal Sokolovic
Bartender

Joined: Jun 19, 2010
Posts: 825
    
    5

You're welcome.
Atah Tabotnjap
Greenhorn

Joined: Mar 17, 2008
Posts: 21
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

Joined: Apr 06, 2010
Posts: 4240
    
    7

Do you know what the largest number you can fit into a byte is?
Kemal Sokolovic
Bartender

Joined: Jun 19, 2010
Posts: 825
    
    5

Check the Tutorial on Primitive Data Types, it's all in there.
Atah Tabotnjap
Greenhorn

Joined: Mar 17, 2008
Posts: 21
SO why is it not 127. How does it come to 46 ?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13875
    
  10

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Atah Tabotnjap
Greenhorn

Joined: Mar 17, 2008
Posts: 21
Thank you very much man. This is very helpful.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36496
    
  16
It shows you ought to beware of casting. It doesn’t always do what you expect.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Code Interpretation
 
Similar Threads
using the math class for rounding numbers
Comparison with NaN
The Same Doubt Again
Enum example from Java Language Specification does not compile.
Rounding Doubles to Two Decimal Places