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

234
Vistas
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 Respuestas
Responde la pregunta

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 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