The following code:
public class Example008 {public static void main (string[] args) {char x = ' x '; int i = 0; System.out.println (true? x:65535); 1system.out.println (true? x:65536); 2system.out.println (true? x:i); 3system.out.println (false? 0:x);//4system.out.println (false? i:x);//5}}
Output Result:
x8888x88
Cause Analysis:
For this result, it would be a surprise if you did not understand the conditional expression result type rule. The result type rule of the conditional expression can probably be attributed to the following three articles:
If the second and third operands have the same type, then it is the type of the conditional expression. In other words, you can avoid annoying by bypassing mixed-type calculations.
If the type of an operand is t,t that represents a byte, short, or char, and the other operand is a constant expression of type int, its value can be represented by type T, then the type of the conditional expression is T.
Otherwise, the binary number promotion is applied to the operand type, and the type of the conditional expression is the type after which the second and third operands are promoted.
After understanding the above rules, re-analyze the code:
Output 1, 65535 is the maximum value of int, x is a char type, conforms to rule 2, the output type is char;
The output 2,65536 is a long type, conforms to rule 3, and the output type is the promoted long;
Output 3, although I is a value of type int, but I is not a constant is a variable, so still conforms to rule 3, the output type is int;
Output 4, in accordance with rule 2, the output type is char;
Output 5, which conforms to rule 3, so the output type is int.
This results in the output is at a glance.
(Note: This "Java doubts" series, are bloggers read "Java doubts" original book, the original book on the explanation and example part of the adaptation, and then write a blog post. All examples are tested in person and shared on GitHub. Use these examples to motivate yourself and benefit others. At the same time, all posts in this series will be posted in the blogger's personal public number (search for "Love Ape" or "ape_it") for easy reading. If there is any infringement of the original rights of the author's content, please inform the blogger in time, in order to promptly delete, if the reader has objection to the content of the text or questions, welcome to the Blog or public messages and other ways to discuss together. )
Source code Address: Https://github.com/rocwinger/java-disabuse
This article from "Winger" blog, declined reprint!
Java FAQ Conditional expression result type rule