Operator Overloading in Java

by Szymon LipiƄski
tags: java

C++ has operator overloading. Java does not. Java folks just say the operation overloading is really bad, that it provides bad abstraction and leads to very unreliable and difficult to manage code. That’s why Java doesn’t have operators overloading.

This is why I cannot check if BigDecimal is less than zero in the normal way:

    public something(BigDecimal price) {
        if (price < 0) {
            throw new IllegalArgumentException(
                      "Price cannot be less than 0");
        }
    }

Instead of the above simple code I just have to write this:

    public something(BigDecimal price) {
        if (price.compareTo(BigDecimal.ZERO) == -1) {
            throw new IllegalArgumentException(
                      "Price cannot be less than 0");
        }
    }

This is a kind of a nightmare, why use the compareTo function which returns that cryptic -1, 0, 1 values? I really want to have operator overloading in Java. The code will be much simpler.

Btw even PostgreSQL has operator overloading.