title: How does long to int cast work in Java?
body: <p>This question is <strong>not</strong> about how a <a href="https://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java">long should be correctly cast to an int</a>, but rather what happens when we incorrectly cast it to an int. </p>
  
  <p>So consider this code -</p>
  
  <pre><code>   @Test
      public void longTest()
      {
          long longNumber = Long.MAX_VALUE;
          int intNumber = (int)longNumber; // potentially unsafe cast.
          System.out.println("longNumber = "+longNumber);
          System.out.println("intNumber = "+intNumber);
      }
  </code></pre>
  
  <p>This gives the output - </p>
  
  <pre><code>longNumber = 9223372036854775807
  intNumber = -1
  </code></pre>
  
  <p>Now suppose I make the following change-</p>
  
  <pre><code>long longNumber = Long.MAX_VALUE - 50;
  </code></pre>
  
  <p>I then get the output - </p>
  
  <pre><code>longNumber = 9223372036854775757
  intNumber = -51
  </code></pre>
  
  <p>The question is, <strong>how</strong> is the long's value being converted to an int?</p>