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

231
Visualizações
Is this a scenario where a java boolean can be null? Why does this code compile?

We recently ran into a bug in production that I found to be very interesting. My longtime understanding is that a Java boolean can only be false, or true. However, it seems in a Ternary Operator it can ultimately resolve to null, and it never produced a compile error, and built all the way to production. I'm very suprised the following code does not generate a compile error. Does anyone know why it compiles just fine? Imho it should not compile! The value it ultimately resolves to is a native boolean.

boolean por = (str == null || str.length() == 0) ? null : "true".equalsIgnoreCase(str);
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Does anyone know why it compiles just fine?

Ultimately, because of autoboxing / autounboxing.

When the compiler processes a ternary expression, it uses the second and third operands to choose the result type of the expression. In your case, the second has null type and the third has (primitive) boolean type. These are not directly compatible, but because of autoboxing, both are compatible with type Boolean. The result of the expression therefore has type Boolean, which does support null.

Because of autounboxing, it is allowed to assign a value of type Boolean to a variable of type boolean, but this will fail with a NullPointerException in the event that the value being assigned is null, just as if you had invoked the booleanValue() method on it. I presume that this is the error you observed in production.

This is one of the gotchas of autoboxing.

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