Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Ternary operator not the same as if-then-else?

807588Jul 15 2009 — edited Jul 15 2009
I've discovered today that I do not actually understand how the ternary operator works. Have a look at the following sample code:

Integer intValue = 5;
Double doubleValue = 6.0;
boolean useDouble = false;

// Using Ternary
Number num = (useDouble) ? doubleValue : intValue;
System.out.println(num + "\t" + (num instanceof Integer)); // 5.0   false

// Using If-then-else
if  (useDouble) {
	num = doubleValue;
} else {
	num = intValue;
}
System.out.println(num + "\t" + (num instanceof Integer)); // 5    true
I had thought that both cases would give me an instance of Integer... but that is not the case. I'd be grateful if someone could explain the details of why ternary and if/else behave differently.

Thanks!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 12 2009
Added on Jul 15 2009
15 comments
385 views