Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

413
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda