Clarification on Ternary Operator Behavior in Java

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
scoffnike
Posts: 2
Joined: Wed Sep 25, 2024 4:19 am
Contact:

Clarification on Ternary Operator Behavior in Java

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

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Clarification on Ternary Operator Behavior in Java

Post 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

Post Reply

Who is online

Users browsing this forum: No registered users and 34 guests