title: How can I check if multiplying two numbers in Java will cause an overflow?
body: <p>I want to handle the special case where multiplying two numbers together causes an overflow. The code looks something like this:</p>
  
  <pre><code>int a = 20;
  long b = 30;
  
  // if a or b are big enough, this result will silently overflow
  long c = a * b;
  </code></pre>
  
  <p>That's a simplified version. In the real program <code>a</code> and <code>b</code> are sourced elsewhere at runtime. What I want to achieve is something like this:</p>
  
  <pre><code>long c;
  if (a * b will overflow) {
      c = Long.MAX_VALUE;
  } else {
      c = a * b;
  }
  </code></pre>
  
  <p>How do you suggest I best code this?</p>
  
  <p>Update: <code>a</code> and <code>b</code> are always non-negative in my scenario.</p>