-1

Possible Duplicate:
What is a Question Mark “?” and Colon “:” Operator Used for?
Question mark in java code

I am writing codes for a RBG to HSV converter. I have this line:

var d = (r==minRGB) ? g-b : ((b==minRGB) ? r-g : b-r);

i dont really understand what the "?" and the ":" means here.

Community
  • 1
  • 1
Parvesh
  • 409
  • 1
  • 7
  • 17

7 Answers7

3

This is the short way to make a condition :

  Condition ? Statment1 : Statement2;

Means

  If (Condition) {Statement1} else {Statement2}
Rafik Bari
  • 4,867
  • 18
  • 73
  • 123
  • how can this answer get upvotes? it's simply wrong. Terinary operators do not work for statements in java – gefei Oct 18 '12 at 14:14
2

This is called ternary operator in java.

Based on java tutorial

Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands.

If first expression results in true, then assign second operand as value, otherwise third operand as value.

kosa
  • 65,990
  • 13
  • 130
  • 167
2

Its Ternary Operator:

C = condition? A : B

is equivalent to

 if (condition){
  C=  A;
 } else{
   C=  B;
 }

It also support nesting i.e. C = condition1? A : condition2?D:E, which is equivalent to

 if (condition1){
   C=  A;
 } else if (condition2){
   C=  D;
 } else{
   C= E;
 }
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
1

It means

if (r==minRGB)
  d = g-b
else
  if(b==minRGB)
     d=r-g
  else
    d=b-r
mat
  • 1,645
  • 15
  • 36
0

Its called ternary operator (?:): -

System.out.println(condition? value1 : value2);

The above expression is evaluated like: -

if (condition) {
    System.out.println(value1); 
} else {
    System.out.println(value2);
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

In c-based languages, it means: ? :

Its short-hand for an if-else, basically.

CodeChimp
  • 8,016
  • 5
  • 41
  • 79
0

it work similar to if than else

if (r==minRGB)
    d = g-b;
}else{
    if  (b==minRGB)
    {
        d = r-g;
    }else{
        d = b-r;
    }
}
Minion91
  • 1,911
  • 12
  • 19