Why System.out.print(ternary operator) print float in output?

Loren :

I was going through some java interview questions MCQ where I found this code snippet, of which I didn't understand the output, though its only a 2 line code.

int a = 8;
System.out.println(((a<8)? 9.9 : (int)9));

Output is 9.0 I didn't understand why it is not 9 ?

Hacı Celal Aygar :

Because you are not casting all of them . you are just casting second result to int.

But don't forget first result is float so all of structure must be same type. You need to cast all of them as same type like int or float.

int a = 8;
System.out.println(""+ (int)( (a<8)? 9.9 :  9));

output :

9

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=238680&siteId=1