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

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)

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.

Parenthesis, Comma Operator and Ternary operator combination equivalent in java

Can any one explain what below statement is doing ? Actually I want to translate code shown here in java, so its real code
w = (m<3?y--,m+=13:m++,d+153*m/5+15*y+y/4+19*c+c/4+5);
I searched a lot but not able to found what this statement is doing. Can anyone explain it and help me to convert it into Java code ? I never seen combination of Unary Operators in Ternary Operators in C language. Sorry for simple question if it is but I did not understand it.
This:
w = (m<3?y--,m+=13:m++,d+153*m/5+15*y+y/4+19*c+c/4+5);
Works out to be the same as this:
if (m<3) {
y--;
m+=13;
} else {
m++;
}
w = (d + (153*m/5) +(15*y) + (y/4) + (19*c) + (c/4) + 5);
Now for the explanation. There is an instance of the ternary operator here. The second clause is an expression which allows for the comma operator, while the third clause is a conditional expression meaning it can't include the comma operator (not without surrounding parenthesis, at least). This means that the first comma you see is part of the second clause while the second comma marks the end of the conditional.
So the expression with implicit parenthesis would look like this:
w = (((m<3)?(y--,m+=13):m++), (d + (153*m/5) +(15*y) + (y/4) + (19*c) + (c/4) + 5));
And the part that makes up the conditional is:
(m<3)?(y--,m+=13):m++
And because this is the left operand of the comma operator, the result of the expression isn't used so it can be pulled out of the larger expression:
(m<3)?(y--,m+=13):m++
w = (d + (153*m/5) +(15*y) + (y/4) + (19*c) + (c/4) + 5);
And the conditional can then be further translated into an if/else block as above.
I'll try.
m<3?
Is essentially
if (m < 3)
If it evaluates as true, y is decremented and 13 is added to m.
If it evaluates as false, m is incremented and then I think that w is set to whatever the result of "d+153m/5+15y+y/4+19*c+c/4+5" is.
You can de-obfuscate it quite a bit by dropping the conditional and comma operators:
if(m<3)
{
y--;
m+=13;
}
else
{
m++;
}
w = d + 153*m/5 + 15*y + y/4 + 19*c + c/4 + 5;

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;
}

ternary operator not working

Netbeans is saying that my ternary operator isn't a statement. How come?
int direction;
direction = (Math.random() < 0.5) ? 0 : 1; // direction is either L or R (0 or 1)
direction == 0 ? System.out.print('L') : System.out.print('R');
I tried it's if/then/else counterpart and it works fine:
int direction;
direction = (Math.random() < 0.5) ? 0 : 1; // direction is either L or R (0 or 1)
if(direction == 0){
System.out.print('L');
} else {
System.out.print('R');
}
The statements in the ternary operator need to be non-void. They need to return something.
System.out.println(direction == 0 ? 'L' : 'R');
A ternary operator is intended to evaluate one of two expressions, not to execute one of two statements. (Invoking a function can be an expression if the function is declared to return a value; however, System.out is a PrintStream and PrintStream.print is a void function.) You can either stick with the if...else structure for what you're trying to do or you can do this:
System.out.print(direction == 0 ? 'L' : 'R');
NOTE: The comment by #iamcreasy points out a bit of imprecision in how I phrased things above. An expression can evaluate to nothing, so what I should have said was that a ternary operator evaluates one of two non-void expressions. According to the Java Language Specification §15.25:
It is a compile-time error for either the second or the third operand
expression to be an invocation of a void method.
From the JLS section 15.25. Conditional Operator ?:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
both the second and third operand expression here:
direction == 0 ? System.out.print('L') : System.out.print('R');
are void so this is a not a valid use of a ternary expression. You could either stick to the if else or use something similar to this alternative:
System.out.print( direction == 0 ? 'L' : 'R' );
Also the logic here is not correct:
direction = (int)(Math.random() * 1);
direction will always evaluate to 0 since Math.random() generates numbers in the range [0.0,1.0) which means it does not include 1.0 and casting a double to int will just drop the decimals. Using nextInt(2) is a good alternative.

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

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

Categories

Resources