Reputation: 47
First of all, apologies for the following question, i am new to java, i have taken the example from a book but it fails to completely explain itself.
I have been reading about the ? operator and how it functions and using the below as an example to learn from:
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10
k = i < 0 ? -i : i; //get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
I understand how the first part gives the result of 10. But i cannot follow how the second part gives the result of 10?
Apologies if this is plainly obvious.
Upvotes: 0
Views: 2987
Reputation: 200
Since the ternary operator evaluates i < 0
in your following line of code:
k = i < 0 ? -i : i; //get absolute value of i
If true k = -i
else false k = i
And as the others mentionned, -(-10) == 10
And I believe this is the output you want since you are trying to get the absolute value of a number, so if it is negative, print out it's positive value.
Upvotes: 1
Reputation: 521
The conditional operator is used to decide which of two values to assign to a variable.
It takes the form:
type variableName = (boolean condition) ? valueIfTrue : valueIfFalse;
In your case you have:
public static void main(String[] args){
int i, k;
i = -10;
k = i < 0 ? -i : i; //get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
So, we are saying:
i < 0, well i is equal to -10 and is therefore less than 0. therefore the true condition is assigned, which has the value of -i.
Since -(-10) = -*-10 = 10 [i.e minus times minus is plus], the output is 10.
Upvotes: 0
Reputation: 452
i gets set to -10 and then k checks if i < 0, which it is.
Therefore it performs the first case:
k = -(-10) = 10
Upvotes: 0
Reputation: 21
When you write:
k = i < 0 ? -i : i
it's interpreted as
if(i < 0){
k = -i;
} else {
k = i;
}
So since -10 is < 0, the given expression returns -(-10), that is 10
Upvotes: 0
Reputation: 7335
i = -10
k = i < 0 ? -i : i;
is the same as
k = i < 0 ? -(-10) : i;
gives you +10
Upvotes: 0
Reputation: 317
when setting k, we have the condition
i < 0
followed by the ?, which asks "Is i less than 0. If it is, it will return the first result (-i), and if it is not it will return the second result (i).
It means the same thing as:
if (i < 0){
k = -i;
else{
k = i;
}
Upvotes: 0