FranXh
FranXh

Reputation: 4771

Return value syntax in java

I am not really sure what this method does, or better I am not sure what " : " means. Can someone please help me understand?

private int guess( )
 {
      return isTrue( ) ? A : isFalse(  ) ? B : neither( ) ? C : D;
 }

Upvotes: 2

Views: 7135

Answers (5)

JDGuide
JDGuide

Reputation: 6525

Your doubt is quite obvious. This type of syntax we call terinary operator. The actual syntax I am writing below:

Syntax:

Condition ? True part : False part ;

In the above statement , if condition is executed true then True part will execute if executed false then False Part will executed.

Example:

int x=10;

if(x==10) ? Print 10(true its Manoj) : Print Not 10(false its Anyone else) ;

Output:

Print 10(true its Manoj)*

I think these few lines will help to clear your doubts.

Upvotes: 0

MeBigFatGuy
MeBigFatGuy

Reputation: 28568

this is a ternary

a ? b : c

means (roughly)

if (a)
   return b;
else
   return c;

Upvotes: 3

Balaswamy Vaddeman
Balaswamy Vaddeman

Reputation: 8530

This is called ternary operator.

isTrue()?a:b;

in above code

if isTrue is true a will be returned,otherwise b will be returned.

you have a nested ternary operator.

isTrue( ) ? A :
           isFalse(  )    ? B :
           neither( )     ? C         : D;

which means isTrue is true a returned,else if it is false b returned and if it is neither c returned else d will be returned.

@birryree given ultimate example code.

Upvotes: 0

Borealid
Borealid

Reputation: 98469

The "?:" is the ternary operator. It means "if the condition before the question mark is true", then use the thing before the colon, otherwise the thing after the colon.

The code you posted will return A if isTrue(), B if !isTrue() && isFalse(), C if !isTrue() && !isFalse() && neither(), and D otherwise (!isTrue() && !isFalse() && !neither()).

Upvotes: 0

wkl
wkl

Reputation: 79903

This is a case of nested ternary operators which have the form a ? b : c which evaluates to:

if (a) then b, else c

So your question breaks down to this:

if (isTrue()) {
    return A;
} else if(isFalse()) {
    return B;
} else if(neither()) {
    return C;
} else {
    return D;
}

Upvotes: 8

Related Questions