File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Cattle Drive and the fly likes A question about a line of code. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » This Site » Cattle Drive
Bookmark "A question about a line of code." Watch "A question about a line of code." New topic
Author

A question about a line of code.

Tony VanHorn
Ranch Hand

Joined: Dec 13, 2006
Posts: 74


would somebody explain what is going on with this code. I am really unsure what is meant by it.

Is it the same as


Thanks
Tony

[edited due to a brief moment of clarity]
[ March 16, 2007: Message edited by: Tony VanHorn ]
Katrina Owen
Sheriff

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

Yepp - you got it in one.

The ternary operator (I think that is what it is called, due to it having three arguments) is in the form

Pauline McNamara
Sheriff

Joined: Jan 19, 2001
Posts: 4012
    
    6
Hi Tony,

Yep, you got it, basically. Except that your code should maybe look like this...




...so you wouldn't be declaring a new variable y when you assign the value.


That compact bit of code is called a ternary operator. Here's an excerpt of what wikipedia's entry on it says:

...the ?: operator is used as a shorthand replacement for the if-then-else conditional statement; the general form is condition ? op1 : op2. If condition is true, the statement evaluates as op1; otherwise, it evaluates as op2.


The understandability/readability of the ternary operator has been the subject of a few discussions here, I'll try to dig one up...
Pauline McNamara
Sheriff

Joined: Jan 19, 2001
Posts: 4012
    
    6
Wow, you're quick Katrina! And I like your example way better than the one from wikipedia.

Here's a couple previous conversations about the ternary operator, interesting reading:


http://www.coderanch.com/t/4390/Cattle-Drive/ternary-operator
http://www.coderanch.com/t/3697/Cattle-Drive/Hint-Please

A search of the Cattle Drive on "ternary" brings up a few more too.
Tony VanHorn
Ranch Hand

Joined: Dec 13, 2006
Posts: 74
Thanks ladies. So this is ONLY used in assignment cases? I also just found this in the Just Java book as I was looking for something for the Grains assignment.

Tony
Katrina Owen
Sheriff

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

I don't think it has to be an assignment, as in you could probably do something like this:

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: A question about a line of code.
 
Similar Threads
[easy]Find the number
Query in Strings -Pass by Reference
Comparision
Equation Parser
initialization and if