Page 1 of 1
[HD-OCP17/21-Fundamentals Pg 283, Sec. 12.2.1 - type-of-a-ternary-conditional-expression]
Posted: Wed Sep 25, 2024 1:25 am
by raphaelzintec
Double d = 10.0;
Byte by = 1;
Number n = a == b? d : by;
here ternary send back a Double, not directly a Number
Because if it was directly a Number i wont be able to do this: Double n = a == b? d : by;
Re: [HD-OCP17/21-Fundamentals Pg 283, Sec. 12.2.1 - type-of-a-ternary-conditional-expression]
Posted: Wed Sep 25, 2024 4:21 am
by scoffnike
In this scenario, the ternary conditional expression is returning a Double because d is a Double and by is a Byte. In Java, the ternary operator will promote the result to the highest type, which is Double in this case. To make your expression work as intended, you can cast by to Number explicitly, like this:
Number n = a == b ? d : (Number) by;
This way, both branches of the ternary expression return a Number, allowing you to assign it to a Number variable without issues. If you want to keep the variable as a Double, you can cast n afterward:
Double n = (Double) (a == b ? d : (Number) by);
hill climb racing
This ensures type safety and resolves the issue you're encountering.
Re: [HD-OCP17/21-Fundamentals Pg 283, Sec. 12.2.1 - type-of-a-ternary-conditional-expression]
Posted: Wed Sep 25, 2024 7:00 am
by admin
Did you read the complete topic "Type of a ternary conditional expression" inside section 12.2.1? It explains exactly what you are getting at in quite detail.
Specifically, this part,
The compiler solves this problem by deciding to pick the most specific common superclass of the two types as the type of the expression. In this case, that class is java.lang.Object. By selecting the most specific common super class, the compiler ensures that irrespective of the result of the condition, the value returned by this expression will always be of the same type
Re: [HD-OCP17/21-Fundamentals Pg 283, Sec. 12.2.1 - type-of-a-ternary-conditional-expression]
Posted: Wed Sep 25, 2024 7:25 am
by raphaelzintec
i have read all of this and i dont have any issues
i am just saying that in this scenario ternary doesnt send directly a Number but a double
Re: [HD-OCP17/21-Fundamentals Pg 283, Sec. 12.2.1 - type-of-a-ternary-conditional-expression]
Posted: Wed Sep 25, 2024 7:29 am
by raphaelzintec
even more interesting it send back a double and not a Double
im just sharing here what i learned
Re: [HD-OCP17/21-Fundamentals Pg 283, Sec. 12.2.1 - type-of-a-ternary-conditional-expression]
Posted: Wed Sep 25, 2024 7:29 am
by admin
oh ok, no issue then
