Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this difference in conditional operator

 
Satish Kota
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Joe Harry
Ranch Hand
Posts: 10083
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say this and it compiles, String s=(3>2) ? "Hi Hello" : "3";
 
Satish Kota
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
raja kanak
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wonderful explanation.
 
Joe Harry
Ranch Hand
Posts: 10083
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Barry,

Thanks for the reasonable explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic