What is the meaning of "X ? a : b" notation? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the Java ?: operator called and what does it do?
In some code a ? is used to perform a mathematical equation.
What is it and how do you use it? Is it possible to provide an example and the reason for the final answer of an equation?
int count = getChildCount();
int top = count > 0 ? getChildAt(0).getTop() : 0;

Basically is the ternary operator:
String mood = (isHappy == true)?"I'm Happy!":"I'm Sad!";
if isHappy, then "I'm Happy!". "I'm Sad!" otherwise.

I presume you mean something like x = () ? y : z; notation? If that's the case, then the expression within the parentheses is evaluated as a boolean, if true x = y otherwise x = z

int count = getChildCount();
int top = count > 0 ? getChildAt(0).getTop() : 0;
Means that the top variable will contain the value of getChildAt(0).getTop() if the count variable is greater than 0, else it will equal to 0

My guess is you are referring to the ternary operator, which is used like this:
<some condition> ? <some value> : <some other value>;
For example:
int max = a > b ? a : b;
It's a shorthand for an if and is equivalent to:
int max;
if (a > b) {
max = a;
} else {
max = b;
}
but allows a one-line result in code.
When used well, it can make code much more clear due to its terseness. However caution is advised if the line becomes too long or complicated: The code only remains readable when the terms are brief.

The ? in an evaluative expression is called the ternary operator. It is essentially short-hand for an if() ... else block.
http://en.wikipedia.org/wiki/%3F:

I assume you're referring to the ternary operator. It's shorthand for certain kinds of if statements. Where you're making an assignment, like:
int dozen = (bakersDozen) ? 13 : 12;
Assuming bakersDozen is true, then dozen will be 13. If it's false, it will be 12.

int result = (a > b) ? 1 : 0;
is the same than
int result;
if (a > b)
result = 1;
else
result = 0;

? Is usually a ternary (or tertiary) operator. So let's explain what it is doing.
myValue = (a = b) ? 1 : 0;
The first part is your condition. "Does a equal b?"
The second part is the true response.
The third part is the false response.
So if a is equal to b, myValue will be 1. If a is not equal to b, myValue will be 0.
See http://en.wikipedia.org/wiki/Ternary_operation

Related

how this Ternary Operator work with this statemnt?

i just generate this methode to find max val in some matrix and somehowe i was able to change int val insdie Ternary Operator (java 8)
int max=0, indexToReturn=0;
int size= arr[0].length;
for (int i=1 ; i < size ; i++)
{
//
// ¯\_(ツ)_/¯
max = (!(arr[j][indexToReturn] > arr[j][i])) ? indexToReturn= i : arr[j][indexToReturn] ;
}
return max > 0 || indexToReturn==size-1 ? arr[j][indexToReturn] : null;
(the method compile and working)
im not realy sure evan how its compile from what i saw online Ternary Operator syntax :
variable = Expression1 ? Expression2: Expression3
can someone explain me what im missing here ?
The reason this works is because an assignment is an expression. The value of an assignment is the value assigned. This sounds theoretical, so let us look at an example:
int i, k;
i = (k = 5);
System.out.println(i);
System.out.println(k);
Ideone demo
The value of the expression k = 5 is the assigned value 5. This value is then assigned to i.
Armed with this knowledge, we see that indexToReturn= i is an expression that evaluates to the value of i. When we swap Expression2 and Expression3, the ternary operator breaks because the = i is not evaluated as part of the ternary operator (due to operator precedence). If we set parentheses around Expression2, it works as expected.
I would discourage using the fact that an assignment is an expression. (Ab)using this fact often leads to hard-to-understand code.

What does a "+=" operator inside a ternary operator means?

I came across a code snippet inside the androidx.lifecycle package and I was wondering what does this means.
LiveData.this.mActiveCount += mActive ? 1 : -1;
Where mActiveCount is an int, and mActive is a boolean.
But, as I was writting this question, I think I came with the answer, so if I'm not mistaken the "+=" operator, is used as we normally use the "=" operator.
This means that the order in which the code executes is the following:
the mActive ? 1 : -1; portion executes first.
Once this is resolved, the LiveData.this.mActiveCount += mActive executes. So my real question is:
Is this the correct equivalence of this code?:
int intToAdd = mActive ? 1 : -1;
activeCount += intToAdd;
The operator += is not concerned with ternary operator.
You are checking for a condition using ternary operator and incrementing or decrementing it variable by 1.
a = a + b is equivalent to a += b, assuming we have declared a and b previously.
So, your code LiveData.this.mActiveCount += mActive ? 1 : -1; is equivalent to :-
if(mActive){
LiveData.this.mActiveCount += 1;
}
else{
LiveData.this.mActiveCount -= 1;
}
Your Logic below is also correct:-
int intToAdd = mActive ? 1 : -1;
activeCount += intToAdd;
This line of code adds either 1 or -1 to mAtiveCount, and looks at the boolean mActive to determine whether it adds +1 or -1.
It is exactly equivalent to this chunk of code, where I removed the usage of the tertiary operator and the += operator (and made their function explicit):
int amountToAdd;
if (mActive) {
amountToAdd = 1;
} else {
amountToAdd = -1;
}
LiveData.this.mActiveCount = LiveData.this.mActiveCount + amountToAdd;
I think the line is a bit unclear, but could be made more clear with the judicious use of parenthesis:
LiveData.this.mActiveCount += (mActive ? 1 : -1);
This can be answered by looking up Java operator precedence.
Assignment operators have the absolute lowest precedence, everything else happens first. The conditional expression mActive ? 1 : -1 is evaluated first. then the += is evaluated using the result of the condition expression.
Yes, you are right. There is something called as shorthand in java .
For example :
sum = sum + 1 can be written as sum += 1.
This statement :
LiveData.this.mActiveCount += mActive ? 1 : -1;
This statement really mean to say :
Either do this LiveData.this.mActiveCount += 1 or LiveData.this.mActiveCount += -1 based on mActive's value (true or false)

Java boolean return if statement [duplicate]

This question already has answers here:
Ternary Operators Java [duplicate]
(7 answers)
Closed 6 years ago.
Can someone please explain, in simple English, the logic behind this statement?
return mContainsLoadingRow ? (getContentDataSize() + 1) : getContentDataSize();
Assuming mContainsLoadingRow is a boolean, if mContainsLoadingRow is true,
then return getContentDataSize() + 1.
If not, return getContentDataSize().
Is that the correct way to look at this?
this complete expression is know as Ternary Operator in Java.
Code Statement
mContainsLoadingRow ? (getContentDataSize() + 1) : getContentDataSize();
|| || ||
//boolean expression //return if true //return if false
here in this code
mContainsLoadingRow is a Boolean variable which contains either true or false. you can also change mContainsLoadingRow with any Boolean expression like (a>b or b==a or b <= a etc.)
? (question mark) :- enables us to fine whether it is true or false.
if true the expression (getContentDataSize() + 1) will be return.
if false then expressin getContentDataSize() value will be return.
int x = 0;
if (0 < 1){
x = 2;
}else{
x = 42;
}
// in short:
x = (0<1) ? 2 : 42;
So yes, you are right

Conditional Ternary Operations

First off, I came across this question recently and haven't being able to find a good explanation for it:
int x = (30 > 15)?(14 > 4) ? 1 : 0 : 2;
I have used ternary expression before so I am familiar with them, to be honest I don't even know what to call this expression... I think that it breaks down like this
if (con1) or (con2) return 1 // if one is correct
if (!con1) and (!con2) return 0 // if none are correct
if (con1) not (con2) return 2 // if one but not the other
Like I said I don't really know so I could be a million miles away.
Because of operator precedence in Java, this code:
int x = (30 > 15)?(14 > 4) ? 1 : 0 : 2;
will be parsed as if it were parenthesized as follows:
int x = (30 > 15) ? ((14 > 4) ? 1 : 0) : 2;
(The only operators with lower precedence than ternary ?: are the various assignment operators: =, +=, etc.) Your code can be expressed verbally as:
if (con1) and (con2) assign 1 to x
if (con1) and (not con2) assign 0 to x
otherwise assign 2 to x
EDIT: Nested ternary operators are often formatted in a special way to make the whole thing easier to read, particularly when they are more than two deep:
int x = condition_1 ? value_1 :
condition_2 ? value_2 :
.
.
.
condition_n ? value_n :
defaultValue; // for when all conditions are false
This doesn't work quite as cleanly if you want to use a ternary expression for one of the '?' parts. It's common to reverse the sense of a condition to keep the nesting in the ':' parts, but sometimes you need nesting in both branches. Thus, your example declaration could be rewritten as:
int x = (30 <= 15) ? 2 :
(14 > 4) ? 1 :
0 ;
It's int x = (30 > 15)?((14 > 4) ? 1 : 0): 2; :
if (30 > 15) {
if (14 > 4)
x = 1;
else
x = 0;
} else {
x = 2;
}

Multiple statements if condition is true in shorthand if

I recently discovered the shorthand if statement and after searching online I couldn't find a definite answer.
Is it possible to execute 2 statements if the condition is true/false?
int x = (expression) ? 1 : 2;
for example
int x = (expression) ? 1 AND 2 : 3;
Seeing as i haven't comne across a example where they used it I guess it's not possible but I wouldn't want to miss out.
You're talking about conditional assignment. You should look at what is defined by what you've written:
int x = (expression) ? 1 AND 2 : 3;
That is evaluating 'expression' and if true executing '1 AND 2' then assigning the value to x. If 'expression' evaluated to false, '3' is evaluated and assigned to x. Hence you could definitely do something like this:
int x = (expression) ? GetInt1() + GetInt2() : 345;
What is important is that what you have found is not just a shorthand if. It is conditional assignment.
You can't have a statement return two values and that's all that ternary does. It is not a shorthanded if it is a method persay that returns values

Categories

Resources