Say this and it compiles, String s=(3>2) ? "Hi Hello" : "3";
SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Joined: Feb 08, 2006
Very smart Jothi. My question was not on how to get the output. I want to know why is this difference occurin at the 1st place. Why doesnt JVM throw an error when conditional is used like above in System.out.println statement.
I am assuming you are using Java 5.0. The result of the conditional operator is an Object. In fact it is an Integer object; the 3 (an int) is being auto-boxed into an Integer. Integer (and String) extends Object and implements Serializable and Comparable. The Integer object cannot be directly assigned to String so that's why you get the error in the first case. In the second case, the System.out.println method can take an Object as parameter and prints the Integer object by calling the toString() method.