Reputation: 97
I am learning Java and have a simple question.
In an example of setting a class I see this:
length >= 0 ? length : length * -1
What does it mean?
Thanks.
Upvotes: 1
Views: 532
Reputation: 105
this is Java ternary operator, it means
if(length>=0) {
length = length;
} else {
length = length * (-1);
}
Upvotes: 1
Reputation: 406
This is a ternary expression. If the value before the question mark is true
, the expression equals the first value after the question mark (length
). If the value before the question mark is false
, the expression equals the value after the colon (length * -1
).
Upvotes: 2
Reputation: 22972
This is ternary operator
in java.
ifTrue ? thanThis : otherwiseThis
Upvotes: 2
Reputation: 201439
That is a hackish way of writing Math.abs(length)
. It calculates the absolute value of the length
by using the Conditional Operation ?: (per the JLS)
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Upvotes: 3
Reputation: 10810
The ?
is the Java ternary operator. See http://alvinalexander.com/java/edu/pj/pj010018
Essentially it has form:
[condition] ? [execute if true] : [execute if false]
Upvotes: 2