title: Java: implement long type overflow immunity with assert
body: <p>Here is my code to calculate different operations on rational numbers. Now, my task is to implement additional security with <code>assert</code> to protect it from overflow. I tried to do something, but when I enabled assertion with <code>-ea</code> to JVM, it started to "throw" assertion all the time (even with <code>4 &gt; 5</code> assert condition). <strong>How I can implement this and what is the proper way of doing it on</strong> <code>Long</code> <strong>numbers ?</strong></p>
  
  <pre><code>public class Rational {
  
  private final long numerator;
  private final long denominator;
  private double result;
  
  public Rational(long numerator, long denominator){
      this.numerator = numerator;
      this.denominator = denominator;
      result = (double)numerator/(double)denominator;
  }
  
  public Rational plus(Rational b){
      assert this.denominator * b.denominator &gt;= Long.MAX_VALUE : "Overflow of denominator in 'PLUS'"; //My attempt
  
      long plusDenominator = this.denominator * b.denominator;
      long plusNumerator = ((plusDenominator / this.denominator) * this.numerator) + ((plusDenominator / b.denominator) * b.numerator);
      long gcd = gcd(plusNumerator, plusDenominator);
      return new Rational(plusNumerator / gcd, plusDenominator / gcd);
  }
  
  public Rational minus(Rational b){
      long minusDenominator = this.denominator * b.denominator;
      long minusNumerator = ((minusDenominator / this.denominator) * this.numerator) - ((minusDenominator / b.denominator) * b.numerator);
      long gcd = gcd(minusNumerator, minusDenominator);
      return new Rational(minusNumerator / gcd, minusDenominator / gcd);
  }
  
  public Rational times(Rational b){
      long timesDenominator = this.denominator * b.denominator;
      long timesNumerator = this.numerator * b.numerator;
  
      long gcd = gcd(timesDenominator, timesNumerator);
      return new Rational(timesNumerator / gcd, timesDenominator / gcd);
  }
  
  public Rational divides(Rational b){
      long divDenominator = this.denominator * b.numerator;
      long divNumerator = this.numerator * b.denominator;
  
      long gcd = gcd(divNumerator, divDenominator);
      return new Rational(divNumerator / gcd, divDenominator / gcd);
  }
  
  private long gcd(long p, long q){
      if(q == 0) return p;
      long r = p % q;
      return gcd(q, r);
  }
  
  public static void main(String[] args){
      Rational r1 = new Rational(8, 999999999999999999L);
      Rational r2 = new Rational(8 ,999999999999999999L);
      System.out.println(r1.plus(r2));
  }
  </code></pre>
  
  <p>}</p>