File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Ternary operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Ternary operator" Watch "Ternary operator" New topic

Ternary operator

rachel biji

Joined: Aug 20, 2008
Posts: 4
This code that I wrote


The compilation error being "Not a statement". Cant understand whats wrong.I also tried

(i%2==0)?(System.out.println("even");) System.out.println("odd");) ;
even though it didnt look right

Can You please give me an explanation?

[edit]Disable smilies CR[/edit]
[ August 21, 2008: Message edited by: Campbell Ritchie ]
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575


take this example
String value(){
return 5<3?"true":"false";
meaning of ternary operator:

(condition)?if success:if failure

if you have any confusion work on this in some IDE.

Hope This Helps
Katrina Owen

Joined: Nov 03, 2006
Posts: 1367

I have seen the ternary operator used in two ways. In both, it is evaluated to a value (not to an executable statement).

1) Assignment

2) Returning a value (as in the previous post)

I have never seen it used to execute a statement, like you are attempting.

So for your example:

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45359
More details in this other thread.
I agree. Here's the link:
subject: Ternary operator
It's not a secret anymore!