wood burning stoves 2.0*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Ternary operator" Watch "Ternary operator" New topic
Author

Ternary operator

rachel biji
Greenhorn

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

i%2==0?(System.out.println("even"):System.out.println("odd");

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

Hi,

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
Sheriff

Joined: Nov 03, 2006
Posts: 1344
    
  12
Hi,

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
Sheriff

Joined: Oct 13, 2005
Posts: 36464
    
  15
More details in this other thread.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Ternary operator
 
Similar Threads
Regarding assertion
PLease ignore previous post -Ternary operator
"assert i%2==0 : i--;"question required
Using Threads
Avoiding if else loop