Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

422
Vistas
How to skip evaluating remaining part of arithmetic expression after 0 * ... in Java

In logic expressions remaining part would be skipped if it is unnecessary

boolean b = false && checkSomething( something)
//checkSomething() doesn't get called

What is a good way to achieve the same with arithmetic expressions ?

int i = 0 * calculateSomethig ( something ) 

It is possible to add ifs before * . But is there a more elegant way to solve this problem? Without of adding much stuff into expression, so that expression itself would look as close to original as possible

Why i do not want to use ifs? from

return calculateA() * calculateB()

it'll become bulky and unclear

int result
int a = calculateA();
if (a!=0) {
    result = a*calculateB()
}else{
    result = 0
}
return result
  • 8 lines of code instead of 1,
  • those expressions might be more complex than a*b
  • those expressions represent business logic so i want to keep them clear and easily readable
  • there might be whole bunch of them

Why do i bother with this at all? Because calculation methods might be expensive

  • uses values form other places, where searches and sorts are happening
  • lots of those expressions can be executed at once ( after user event and user should see result "instantly"
  • P( *0 in expression ) >0.5
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

&& and || are called short-circuit operators because they don't evaluate if the JVM will find the value of the whole expression without evaluating the whole expression. For example, the JVM does not have to evaluate the second part of the following expression to tell it evaluates to true:

6 == (2 + 4) || 8 == 9

The JVM does not have to evaluate all of the following expression either to tell it evaluates to false:

9 == 8 && 7 == 7

The multiplication operator (*) is not a short-circuit operator. And so, it does not behave that way. You can do this as you mentioned using if statements. There is no predefined way to do this.

over 4 years ago · Santiago Trujillo Denunciar

0

You can create a structure that uses lambdas to evaluate its arguments lazily:

class LazyMul implements IntSupplier {
    private final IntSupplier [] args;

    private LazyMul(IntSupplier[] args) {
        //argument checking omitted for brevity :)
        this.args = args;
    }

    public static LazyMul of(IntSupplier ... args) {
        return new LazyMul(args);
    }

    @Override
    public int getAsInt() {
        int res = 1;
        for (IntSupplier arg: args) {
            res *= arg.getAsInt();
            if (res == 0)
                break;
        }
        return res;
    }
}

Of course this is even longer but using it is as simple as LazyMul.of(this::calculateA, this::calculateB), so if you use it several times, it's better than having an if every time around.

Unfortunately with complicated (particularly nested) expressions readability suffers, but these are the limitations of Java as a language.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda