title: Number overflow in Java
body: <p>I am tring to implement <strong>C/C++</strong> atoi function in <strong>Java</strong>, below is the code snippet</p>
  
  <pre><code>    for (int j = 0; j &lt; s.length(); j++) {
  
          int digit = Character.digit(s.charAt(j), 10);
          if (sum &lt; limit/10) {
              if (neg) return Integer.MIN_VALUE;
              return Integer.MAX_VALUE;
          }
  
          sum *= 10;
          if (sum &lt; limit + digit) {
              if (neg) return Integer.MIN_VALUE;
              return Integer.MAX_VALUE;
          }
          sum -= digit;
      }
  </code></pre>
  
  <p>For line <code>"if (sum &lt; limit + digit) {"</code>, which is correct, however, if I use <code>"sum - digit &lt; limit"</code>, it will get wrong result, e.g. input "-2147483649", wrong result 2147483647, should be -2147483648.</p>
  
  <p>I figured this out, cuz sum - digit might be overflow, so this come to another question:</p>
  
  <pre><code>    int sum = Integer.MAX_VALUE;
      System.out.println(sum &lt; Integer.MAX_VALUE + 1);
  </code></pre>
  
  <p>Why this prints false? What is the behind logic?</p>