title: Java - weird behavior casting long to int
body: <p>While debugging my Android app I discovered an unexpected behavior when casting a long to an int. For even very low long values (i.e. two digits) casting it to an int resulted in negative numbers. Below is my code and output of my Log.d's. I pass in a long that represents a date in milliseconds.</p>
  
  <pre><code>private int calcNumDaysFrom(long previousDay) {
          long today = new Date().getTime();
          Log.d(TAG, "Today: " + today + " lastDay: " + previousDay + " difference: " + (today - previousDay));
          Log.d(TAG, "Not casted: " + (today - previousDay) / (1000 * 60 * 60 * 24));
          Log.d(TAG, "Casted: " + (int) (today - previousDay) / (1000 * 60 * 60 * 24));
          Long result = (today - previousDay) / (1000 * 60 * 60 * 24);
          return result.intValue();
      }
  </code></pre>
  
  <blockquote>
    <p>LandingPageFragment: Today: 1495231339845 lastDay: 1492488000000 difference: 2743339845</p>
    
    <p>LandingPageFragment: Not casted: 31</p>
    
    <p>LandingPageFragment: Casted: -17</p>
  </blockquote>
  
  <p>As you can see I "fixed" my problem by using a Long object and the member method .intValue(), but I would really like to know where the disconnect is occurring. Is it a 2-compliment issue? Is there a way I can predict when this type of thing will happen so I know if I have to use a Long object?</p>