Problem understanding a java statement!  
Author Message
Moham12345





PostPosted: 2007-3-7 7:19:00 Top

java-programmer, Problem understanding a java statement! Please could somebody help me understand what this statement is doing,

k = (k1 > s0) ? k1 : s0;

what is this statement doing?

what will k be equal to if
k1 = 3 and s0 = 2 ?

 
Tom Hawtin





PostPosted: 2007-3-7 7:34:00 Top

java-programmer >> Problem understanding a java statement! Moham12345 wrote:
>
> k = (k1 > s0) ? k1 : s0;
>
> what is this statement doing?

if (k1 > s0) {
k = k1;
} else {
k = s0;
}

Or, assuming suitable types:

k = Math.max(k1, s0);

Tom Hawtin
 
Adam Maass





PostPosted: 2007-3-7 10:02:00 Top

java-programmer >> Problem understanding a java statement!
"Moham12345" <email***@***.com> wrote:
> Please could somebody help me understand what this statement is doing,
>
> k = (k1 > s0) ? k1 : s0;
>
> what is this statement doing?
>
> what will k be equal to if
> k1 = 3 and s0 = 2 ?
>

The trick is in understanding the ternary operator,

? :

This takes three operands,

<op1> ? <op2> : <op3>


op1 must have a boolean type; op2 and op3 must have compatible types.

The value of the expression is op2 if op1 is true, op3 otherwise.