Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the following Java program giving strange output?

Tags:

java

puzzle

I found below puzzle in Java Puzzlers,

public class DosEquis {
    public static void main(String[] args) {
        char x = 'X';
        int i = 0;
        System.out.print(true  ? x : 0);
        System.out.print(false ? i : x); 
    }
}

I tried this code and run it as well but output was not came as per my guess,

my guess output should be : XX but in
reality output is : X88

I tried lot to understand but i couldn't,can anybody give us the explanation? why is the different output is coming ? since i was able to understood that first print() that will print variable char x character value, but second print() printing 88 an ASCII- representation of value in char x.if i simplify the ternary operators expression in second print() like this

if(false){
    System.out.print(i);
}else{
    System.out.print(x);
}

then output is coming XX,quite strange, can anybody lighten this problem?

It would be great help for me to understand ternary operators.

Thanks in advance!

like image 280
Jameer Mulani Avatar asked Dec 04 '22 06:12

Jameer Mulani


1 Answers

The reason for this behavior is that a ternary has one result type that the compiler has to choose in advance, and the flavor of print called in response.

In the true ? x : 0 case, 0 is treated as a char value, and print(char) is invoked. In the second case, since i is an int, x is also implicitly cast to int (a widening cast) and print(int) is invoked, yielding numeric output. The opposite, casting i to char implicitly, is illegal, because it could lose precision.

The implications of statically resolving the type can be shown with this example - not with print, because there is a print(Object), but consider this:

void method(boolean b);
void method(Integer i);
...
method(cond? false:0);

No matter what cond is, there is an overload compatible with the parameter. However, the compiler needs to chose one overload, which is not possible at compile time. The compiler will autobox both and assign the expression as Object*, but there is no method(Object).


*actually, my compiler said "The method method(boolean) in the type Test is not applicable for the arguments (Object&Serializable&Comparable<?>)", but the point stands.

like image 90
Silly Freak Avatar answered Dec 17 '22 22:12

Silly Freak