Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Hamish Jones   on Aug 24 In Java Category.

  
Question Answered By: Omar Walker   on Aug 24

This does not happen because you assigned the values  to variables  and
used them, but rather than what operations you are doing on what data
types. In your first program, distance  is declared as long  whereas the
numbers 1000, 186000, 24, 60 and 60 are of type  int. Now int  in Java is
always a signed 32-bit integer value. I assume you know how signed and
unsigned int works. Basically numbers that start with a 0 are positive
and with a 1 are negative. I am not going to go into binary arithmetic
here, but when this line is executed: distance=1000*186000*24*60*60; the
calculation returns a binary value with leading 1's. ( 111010011101
10101110011110111100000000000000 to be exact, I have included the split
to show the overflow of the 32 bits allowed. When you do a 2's
complement to the existing 32-bits, which is complementing each bit and
adding a 1 to the result, you get 1010001100001000100000000000000, which
is, voila, you guessed it : 1367621632 with a negative sign in front of
it.) The program, while using it in binary form, simply represents it in
negative form because of the leading 1's. However, in your second
program, you are breaking up your calculations into manageable chunks.
So the line seconds=days*24*60*60; returns
00000101001001100101110000000000, which is positive and accepted. And
since distance and seconds  are of type long, an automatic conversion
occurs and the resultant answer, which is
00000000000000000000111010011101 10101110011110111100000000000000, is
positive and you get your correct  answer.
Also, this situation is not just for Java but for any programming
language and is a serious warning of what will happen if you don't mind
your data types. I seriously hope this made this situation a lot more
clearer. :-P Just kidding. Have fun.

Share: 

 

This Question has 1 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on java bug ? Or get search suggestion and latest updates.


Tagged: