From the course: Oracle Java Certification: 2. Operators and Decision Statements
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Ternary operators - Java Tutorial
From the course: Oracle Java Certification: 2. Operators and Decision Statements
Ternary operators
- Now that we have seen examples that use nested if statements to conditionally assign values to variables, a more succinct way to express such logic is to use a conditional expression with a ternary operator. In this example, we initialize the variable comment to a different value depending on the range in which the score value falls. One of the three possible values will be assigned to comment. Note that all the possible values must be of the same type, otherwise, the code won't compile. What would this code output? Because the score is two, neither of the conditional expressions values to two, and therefore the last value is used for the assignment. Another use for conditional expression is to shorten conditional checks. This code example checks whether there's a pair of matching elements from arrays a and b. Two elements match if they're both no or are identical according to the definition of the equals…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.