Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

java - Why is my char printing as a number instead of a character?

As per the Java ternary operator expression ? statement1 : statement2, if expression is true then statement1 will be executed, if expression is false then statement2 will be executed.

But when I run:

// some unnecessary codes not displaying
char y = 'y';
int i = 0;
System.out.print(false ? i : y);

I am expecting it to print y but its printing 121, why?

EDIT As per the manouti answer, the compiler interprets as int, but if that is the case then why I am seeing dead code at i?

If I do System.out.print(false ? 0 : x); then I am getting y, so why in this case doesn't the compiler interpret as int?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

121 is the integer representation of the character y. Since you provided i as part of the expression, the compiler interprets it as a call to System.out.print(int) instead of System.out.print(char).

Note that changing to System.out.print(false ? (char)i : y); prints y.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...