x = (boolean expression) ? value to assign if true : value to assign if false
Let's take a look at a conditional operator in code:
class Salary {
public static void main(String [] args) {
int numofPets = 3;
String status = (numofPets<4) ? "Pet limit not exceeded"
: "too many pets";
System.out.println("This pet status is " + status);
}
}
You can read the preceding code as
Set numofPets equal to 3. Next we're going to assign a String to the status variable. If numofPets is less than 4, assign "Pet limit not exceeded" to the status variable; otherwise, assign "too many pets" to the status variable.
A conditional operator starts with a boolean operation, followed by two possible values for the variable to the left of the assignment ( = ) operator. The first value (the one to the left of the colon) is assigned if the conditional (boolean) test is true, and the second value is assigned if the conditional test is false. You can even nest conditional operators into one statement:
class AssignmentOps {
public static void main(String [] args) {
int sizeOfYard = 10;
int numOfPets = 3;
String status = (numOfPets<4)?"Pet count OK"
:(sizeOfYard > 8)? "Pet limit on the edge"
:"too many pets";
System.out.println("Pet status is " + status);
}
}
Don't expect many questions using conditional operators, but remember that conditional operators are sometimes confused with assertion statements, so be certain you can tell the difference.
Given:
11. String[] elements = {"for", "tea", "too"};
12. String first = (elements.length>0) ? elements[0] : null;
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The variable first is set to null.
D. The variable first is set to elements[0].
沒有留言:
張貼留言