File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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: 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

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: 24
Thanks man
Kemal Sokolovic
Bartender

Joined: Jun 19, 2010
Posts: 825
    
    5

You're welcome.
Atah Tabotnjap
Greenhorn

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

Joined: Apr 06, 2010
Posts: 4343
    
    8

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: 24
SO why is it not 127. How does it come to 46 ?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

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: 24
Thank you very much man. This is very helpful.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37988
    
  22
It shows you ought to beware of casting. It doesn’t always do what you expect.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Code Interpretation
 
Similar Threads
Rounding Doubles to Two Decimal Places
Comparison with NaN
Enum example from Java Language Specification does not compile.
The Same Doubt Again
using the math class for rounding numbers