Can someone explain the question mark in the following code? Also INITIAL_PERMANCE is a static final constant in the code but what is the last line of synatax called?
Synapse(AbstractCell inputSource, float permanence) {
_inputSource = inputSource;
_permanence = permanence==0.0 ?
INITIAL_PERMANENCE : (float)Math.min(1.0,permanence);
}
The ? and : are part of the java conditional operator. Sometimes called the ternary operator because it is the only operator in Java that takes 3 arguments.
This is essentially an inline IF / THEN / ELSE block.
_permanence = permanence==0.0 ?
INITIAL_PERMANENCE : (float)Math.min(1.0,permanence);
Can be rewritten as follows:
if (permanence == 0.0)
_permanence = INITIAL_PERMANENCE;
else
_permanence = (float) Math.min(1.0,permanence);
The general form of the conditional operator is
<Test returning a boolean> ? <value for if test is true> : <value for if test is false>
It's called the Java ternary operator (as Hovercraft said), and is used like this:
type variableName = (statement) ? value if statement is true: value if false;
This is the most common way it is used.
[Optional Variable] = ( Boolean Test ) ? (Execute this if True) : (Execute this if false)
This is the ternary operator. It works like an if-else statement.
Decomposed, the statement is similar to this:
if(permanence == 0.0) {
_permanence = INITIAL_PERMANENCE;
} else {
_permanence = (float)Math.min(1.0,permanence);
}
Its use is limited in situations in which the meaning is very clear. Ternary operators can confuse, so use them sparingly.
The last statement:
(float)Math.min(1.0, permanence)
is called a type cast. You're casting the result of Math.min(), which returns a double, to that of a float. You'll have to read up more on what floating point numbers are to see the value of doing that is.
This is equal to an if else statement in an inlined manner.Equivalent to
_permanence =
{// A kind of anonymous routine for assignment
if(permanence==0.0)
{ INITIAL_PERMANENCE }
else
{ (float)Math.min(1.0,permanence)}
}
A good explanation is on oracle site about ternary operators
Related
I have tried to leave the else part empty for ternary operator ( for int variables ), but I can't do it what is the problem?
here is the code
int FemaleCounter=0, MaleCounter =0, StateCounterIn =0 , StateCounterOut =0;
if(arr[0].equals("male") ) {
MaleCounter ++;
}
if(arr[0].equals("female") ) {
FemaleCounter ++;
}
if(arr[1].equals("in")) {
StateCounterIn++;
}
if(arr[1].equals("out") ) {
StateCounterOut++;
}
here is the ternary operator form :-
MaleCounter = arr[0].equals("male") ? MaleCounter++ : ;
FemaleCounter = arr[0].equals("female") ? FemaleCounter++ : ;
StateCounterIn = arr[1].equals("in") ? StateCounterIn++ : ;
StateCounterOut = arr[1].equals("out") ? StateCounterOut++ : ;
Thanks for your answers .
MaleCounter += arr[0].equals("male") ? 1 : 0;
FemaleCounter += arr[0].equals("female") ? 1 : 0;
StateCounterIn += arr[1].equals("in") ? 1 : 0;
StateCounterOut += arr[1].equals("out") ? 1 : 0;
A ternary expression must deliver a result. Also ++ inside and then assigment is overkill.
As its name indicates, the ternary operator takes three operands. You cannot omit any of them any more than you can omit either operand of any of the binary operators (*, /, ., etc.), or the one operand of a unary operator (++, --, among others).
The fact that an expression using the ternary operator is in some ways analogous to an if / then / else statement is irrelevant here, but the key distinction is important: an expression in the ternary operator evaluates to a value. It is necessary to designate that value for each alternative.
Observe, further, that your analogy is false anyway. You might consider fixing the syntax issue by using forms similar to this ...
// useless
MaleCounter = arr[0].equals("male") ? MaleCounter++ : MaleCounter;
..., but that does not have the same effect as your corresponding if statement, because in the case where the increment is performed, the pre-increment value is afterward assigned back to MaleCounter.
I find your original code pretty clear, but if for some reason you insist on using the ternary operator, then one of these is the model I would follow:
MaleCounter = arr[0].equals("male") ? MaleCounter + 1 : MaleCounter;
FemaleCounter += (arr[0].equals("female") ? 1 : 0);
In logic expressions remaining part would be skipped if it is unnecessary
boolean b = false && checkSomething( something)
//checkSomething() doesn't get called
What is a good way to achieve the same with arithmetic expressions ?
int i = 0 * calculateSomethig ( something )
It is possible to add ifs before * . But is there a more elegant way to solve this problem? Without of adding much stuff into expression, so that expression itself would look as close to original as possible
Why i do not want to use ifs?
from
return calculateA() * calculateB()
it'll become bulky and unclear
int result
int a = calculateA();
if (a!=0) {
result = a*calculateB()
}else{
result = 0
}
return result
8 lines of code instead of 1,
those expressions might be more complex than a*b
those expressions represent business logic so i want to keep them
clear and easily readable
there might be whole bunch of them
Why do i bother with this at all?
Because calculation methods might be expensive
uses values form other places, where searches and sorts are happening
lots of those expressions can be executed at once ( after user event and user should see result "instantly"
P( *0 in expression ) >0.5
&& and || are called short-circuit operators because they don't evaluate if the JVM will find the value of the whole expression without evaluating the whole expression. For example, the JVM does not have to evaluate the second part of the following expression to tell it evaluates to true:
6 == (2 + 4) || 8 == 9
The JVM does not have to evaluate all of the following expression either to tell it evaluates to false:
9 == 8 && 7 == 7
The multiplication operator (*) is not a short-circuit operator. And so, it does not behave that way. You can do this as you mentioned using if statements. There is no predefined way to do this.
You can create a structure that uses lambdas to evaluate its arguments lazily:
class LazyMul implements IntSupplier {
private final IntSupplier [] args;
private LazyMul(IntSupplier[] args) {
//argument checking omitted for brevity :)
this.args = args;
}
public static LazyMul of(IntSupplier ... args) {
return new LazyMul(args);
}
#Override
public int getAsInt() {
int res = 1;
for (IntSupplier arg: args) {
res *= arg.getAsInt();
if (res == 0)
break;
}
return res;
}
}
Of course this is even longer but using it is as simple as LazyMul.of(this::calculateA, this::calculateB), so if you use it several times, it's better than having an if every time around.
Unfortunately with complicated (particularly nested) expressions readability suffers, but these are the limitations of Java as a language.
I am beginner to android, I am looking at this tutorial and came accross this code:
int temp = (sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;
can some one explain this for me.
May be this question is duplicate, but I don't know what to search for.
It will be great if you can tell me what it is in C# aswell.
(sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;
means
int result;
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER)
result = 1;
else
result = 0;
I am not 100% sure as what you want to be explained, but it seems that you are not understand/knowing about the ternary operator in Java.
It essentially means:
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
temp = 1;
}
else {
temp = 0;
}
Furthermore, I am unsure if this is correct Java code. It seems like you have left out something of your question, as the ternary operator most likely belongs to either an assignment or a return statement.
If you are talking about the parenthesis, question mark, and colon, then... it goes like so
(Condition ? If_condition_is_true_do_this : otherwise_do_this);
Exactly like doing this:
if(Condition)
If_condition_is_true_do_this
else
otherwise_do_this
And it is the same syntax in C#;
This is Java, not C# but ternary operators exist there as well.
About ternary operators, click here.
What the (full) code (not your snippet) does here is to check the sensor variable for equality with class constant Sensor.TYPE_ACCELEROMETER and assign the missing variable on the left with 1 if they are equal or 0 otherwise.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the Java ?: operator called and what does it do?
Maybe this is a duplicated question to some other questions here but I could not find it.
Yesterday I saw a guy using a new way of writing the if statement by using ? and : and I'm not sure what do they all mean.
If someone could point me out to a tutorial or an already answered question I would so much appreciated.
The conditional operator, it's a type of ternary operator
wikipedia - ?:
wikipedia - ternary operation
(condition) ? (what happens if true) : (what happens if false);
Example use:
int a = 1;
int b = (a == 1) ? 2 : (a + 1);
It's a ternary operator. General form:
expr1 ? expr2 : expr3
If expr1 evaluates to true, the returned result is expr2, otherwise it's expr3. Example:
Object obj = (obj != null) ? obj : new Object();
Easy way to initialize an object if it's null.
(statement) ? TRUE : FALSE
Example in pseudocode: a = (5 > 3) ? 1 : 0
If the statement is true, a will be one (which it is), otherwise it will be 0.
That's called a ternary operator, and it's a cute, if sometimes hard to read, way of writing an IF statement.
if ( x == 3) {
do-magic
}
else {
do-other-magic
}
would be expressed like so:
x == 3 ? do-magic : do-other-magic
I've seen this before in code, but forgotten it. Basically it toggles a boolean variable. If it's true, it'll set to false and vice-versa. But unfortunately forgot the syntax.
It's basically a one liner for this:
if (myVar) {
myVar = false;
} else {
myVar = true;
}
It's something like this, but don't know what it's called or the correct syntax of it:
myVar = myVar : false ? true;
How about
myVar = !myVar
?
myVar = myVar ? false : true; is using the conditional operator.
You can just do this though
myVar = !myVar;
Another option is XOR:
myVar ^= true;
It's notable in that only the LHS of the assignment ever changes; the right side is constant and will toggle any boolean variable. Negation's more self-documenting IMO, though.
What you are thinking of is the conditional operator:
myVar = myVvar ? false : true;
(As you see, a lot of people call this "the ternary operator", but that only means that it is an operator with three operands. As it happens, there is only one operator with three operands in this language, but it still says nothing about what the operator does.)
It's of course easier to use the negation operator:
myVar = !myVar;
The smallest code I can think of at the moment. I don't know what its called (if it has a name, as you seem to suggest)
myVar = !myVar
What you're talking about is the "ternary" or "conditional" operator, which does an inline substitution as per a condition.
The syntax is:
condition ? trueValue : falseValue
I usually throw parentheses around my condition, sometimes around the whole conditional operator. Depends on how much I'm trying to delineate it from everything else.
So for example, suppose you want to return the larger of two numbers:
public int max(int a, int b)
{
return (a > b) ? a : b;
}
Notice that it can be substituted into the middle of something else.
Okay, now let's tackle your actual question about toggling a boolean type.
myVar = (myVar) ? false : true;
is how you would do it with the conditional operator. (Again, parentheses aren't required, I just favor them.)
But there's a simpler way to toggle the boolean... using the logical NOT ("!") operator:
myVar = !myVar;
Keep it simple. :-)
if(myVar == true)
{
myVar = false;
}
else if (myVar == false)
{
myVar = true;
}
else
{
myVar = FILE_NOT_FOUND
}
This also works :P
v=v?!v:!v;
There is a ternary operator (wikipedia). Which allows you to write a condensed if-else statement like in the second example.
In java:
myVar = (myVar) ? true : false;
There is also the NOT operator, which toggles a boolean variable. In java that is !. I believe that is what you want.
myVar = !myVar;
public boolean toggle(boolean bool)
{
return !bool;
}
I recently (on my own) found a similar answer to one already stated here. However, the simplest and shortest (non-repeating variable name with least code) answer is:
formControl.disabled ^= 1;
This works best in JavaScript when wanting to toggle boolean, DOM-based attributes (for example, a form control/input's disabled property -- going from a non-editable to edit state). After much searching (with no result that I liked) and some trial and error, I found my solution to be the simplest (however, true instead of a 1 would be clearer -- as was previously posted).
Since this syntax isn't very clear, immediately, I would not advise using it very often (I believe it is appropriate when the variable or property makes the context obvious). I have posted this response (instead of making it a comment) because the context in which the XOR bitwise self-assignment should be used is very important. This "trick" should mostly be avoided when considering best practices.
As others have noted, there are two ways to negate something: "lvalue = !lvalue;" and "lvalue ^= 1;". It's important to recognize the differences.
Saying "lvalue = !lvalue" will cause lvalue to be set to 1 if it was zero, and 0 if it was set to anything else. The lvalue will be evaluated twice; this is not a factor for simple variables, but saying "someArray[index1][index2][index3][index4] = !someArray[index1][index2][index3][index4]" could slow things down.
Saying "lvalue ^= 1;" will cause lvalue to be set to 1 if it was 0, 0 if it was 1, and something else if it was neither zero nor 1. The lvalue need only be specified or evaluated once, and if the value is known to be either zero or 1, this form is likely to be faster.
Too bad there's no auto-negate operator; there are times such a thing would be handy.
You can also use the binary form of negation as shown here.
if ((v == true) && !(v = false)) {
v != true; /* negate with true if true. */
} else {
v =! false; /* negate with false if false. */
}