Page 1 of 1

Clarification on Ternary Operator Behavior in Java

Posted: Wed Sep 25, 2024 4:23 am
by scoffnike
Hello everyone,

I hope you're all doing well! I'm currently preparing for the OCA/OCP Java Programmer Certification and I've come across a question regarding the behavior of the ternary operator that I find a bit confusing.

In the following code snippet:

Code: Select all

Double d = 10.0;
Byte by = 1;
Number n = a == b ? d : by;
I noticed that the ternary expression seems to return a Double instead of a Number. My understanding is that the result should be promoted to the highest type in the expression. However, I expected it to return a Number since by is of type Byte.
slice masters
Could someone please clarify why the expression behaves this way and how I can ensure it returns a Number? Any insights or explanations would be greatly appreciated!

Thanks in advance!

Re: Clarification on Ternary Operator Behavior in Java

Posted: Wed Sep 25, 2024 5:58 am
by admin
The ternary operator returns least upper bound. Check out this thread. It explains the ternary opertor type: https://enthuware.com/forum/viewtopic.php?f=2&t=6375