aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why this difference in conditional operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why this difference in conditional operator" Watch "Why this difference in conditional operator" New topic
Author

Why this difference in conditional operator

Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
Ranchers,
Please consider the following code:



When compiled the compiler gives an error.

test.java:5: incompatible types
found : java.lang.Object&java.io.Serializable&java.lang.Comparable<? extends j
ava.lang.Object&java.io.Serializable&java.lang.Comparable<?>>
required: java.lang.String
String s=(3>2) ? "Hi Hello" : 3;


But if i give the conditional operator directly in the System.out.println i dont get any error and the code compiles and runs fine.Here is the code:



the output is
Hi Hello

Can you please explain this difference in output?


SCJP 5.0 77%
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9513
    
    2

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!
Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
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.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
raja kanak
Ranch Hand

Joined: Oct 18, 2006
Posts: 135
Wonderful explanation.


live
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9513
    
    2

Barry,

Thanks for the reasonable explanation.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why this difference in conditional operator