The conditional operator: ?
The ? can be used for very simple Boolean expressions in place of if/else code
The conditional operator: ?
The ? can be used for very simple Boolean expressions in place of if/else code
The ? is the conditional operator. It can be used for very simple Boolean expressions in place of if/else code.
The code below says that if the Boolean expression (num<10) is true then s will be assigned the value "Yes".
If the Boolean expression is false, S will be assigned the value "No"
int num = 8;
String s=(num < 10) ? "Yes": "No";
this.Text = s;
The code above can also be written as:
int num = 8;
this.Text = (num < 10) ? "Yes" : "No";
In this example below, the String passFail gets the value "Pass" if the Boolean expression is true, "Fail" otherwise.
int grade = 80;
String passFail;
passFail = (grade>65) ? "Pass" : "Fail";
this.Text = passFail;
Please note that in an actual program the values for num and grade would come from controls such as scroll bars or text boxes, or read from a file.