1

Everyone knows how simple arithmetic in Java works for primitives:

int one = 1,two = 2,three = one + two;
double four = (one + two) / three;
if(four % 1 == 0){
     System.out.println("Yay for simple maths!");
} else{
  throw new RealityError("http://www.youtube.com/watch?v=H91rPIq2mN4");
 }

But the moment that you leave primitives things become complicated fast! Attempting to repeat the previous simple arithmetic is quite the challenge!

BigInteger bigOne = BigInteger.ONE, bigTwo = BigInteger.valueOf(2),
            bigThree = bigOne.add(bigTwo);
    BigDecimal bigFour = new BigDecimal(bigThree.divide(bigOne.add(bigTwo)));
    if (BigInteger.valueOf(bigFour.longValueExact()).mod(BigInteger.ONE).equals(BigInteger.ZERO)) {
        System.out.println("Yay for simple maths?!?!");
    } else {
        throw new RealityError("http://www.youtube.com/watch?v=H91rPIq2mN4");
    }

Why aren't annotations used for operators like +, -, *, or /? Such as @DefaultAddOperator for a class that extends Number. Or, in the BigInteger class, why can't it implement an interface that simply states what operation to do when an operator is called on the class. This notion isn't too far fetched, I mean it's used with "Hello World!".toString() and the overloaded operator +, and would simplify the above class based arithmetic considerably.

Sarah Szabo
  • 10,345
  • 9
  • 37
  • 60
  • 1
    Where would such an annotation be placed? – Matt Ball Jan 24 '14 at 05:34
  • 2
    Please search for "operator overloading [java]". This question is a duplicate of many older questions. It is a complex question and there is no answer that will actually solve it for you. – Erwin Bolwidt Jan 24 '14 at 05:34

1 Answers1

1

This is because java doesn't support operators overloading, as in . Have a look at or languages, they do. Moreover, groovy uses BigDecimal as it's primary type for non-integer operations. And it supports all of these basic operations.

Alexander Tokarev
  • 2,743
  • 2
  • 20
  • 21