title: java number exceeds long.max_value - how to detect?
body: <p>I'm having problems detecting if a sum/multiplication of two numbers exceeds the maximum value of a long integer.<br>
  Example code:  </p>
  
  <pre><code>long a = 2 * Long.MAX_VALUE;
  System.out.println("long.max * smth &gt; long.max... or is it? a=" + a);
  </code></pre>
  
  <p>This gives me <code>-2</code>, while I would expect it to throw a <code>NumberFormatException</code>...</p>
  
  <p>Is there a simple way of making this work? Because I have some code that does multiplications in nested IF blocks or additions in a loop and I would hate to add more IFs to each IF or inside the loop.</p>
  
  <p>Edit: oh well, it seems that this answer from another question is the most appropriate for what I need: <a href="https://stackoverflow.com/a/9057367/540394">https://stackoverflow.com/a/9057367/540394</a><br>
  I don't want to do boxing/unboxing as it adds unnecassary overhead, and this way is very short, which is a huge plus to me. I'll just write two short functions to do these checks and return the min or max long.</p>
  
  <p>Edit2: here's the function for limiting a long to its min/max value according to the answer I linked to above:  </p>
  
  <pre><code>/**
   * @param a : one of the two numbers added/multiplied
   * @param b : the other of the two numbers
   * @param c : the result of the addition/multiplication
   * @return the minimum or maximum value of a long integer if addition/multiplication of a and b is less than Long.MIN_VALUE or more than Long.MAX_VALUE
   */
  public static long limitLong(long a, long b, long c)
  {
      return (((a &gt; 0) &amp;&amp; (b &gt; 0) &amp;&amp; (c &lt;= 0))
          ? Long.MAX_VALUE
          : (((a &lt; 0) &amp;&amp; (b &lt; 0) &amp;&amp; (c &gt;= 0)) ? Long.MIN_VALUE : c));
  }
  </code></pre>
  
  <p>Tell me if you think this is wrong.</p>