Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!