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
Related
This question already has answers here:
How to use ternary operator(?:) or Null Coalescing operator(??) to write if-else condition?
(5 answers)
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 2 years ago.
Can someone please explain this java syntax for me.
public boolean isDead() { return numFightersAlive() == 0 ? true : false; }
I am new to java and I was wondering what kind of syntax that is. Normally I would create a variable and return the boolean variable but it's my first time seeing a question mark in a code.
After the question mark is the "then" part, after colon is the "else" part.
So this is shorthand syntax for
if (numFightersAlive() == 0) {
return true;
} else {
return false;
}
It can actually be simplified to be just
return numFightersAlive() == 0
This would give an equivalent result
This is called ternary. It's a shortened version of an if, but it's not better than an if all the time.
The syntax of a ternary is as follows:
(condition) ? result in case of being true: result in case of being false
In this case:
The return is asking a condition. Is the condition equal to zero?
If it is true, return will have a true value, if it is false return will have a false value.
public boolean isDead() { return numFightersAlive() == 0 ? true : false; }
I would like to shorten my code by the use of the ?: (if-else-then) comparative operator instead of using the traditional if{}else{} blocks that inconveniently tend to take over the screen. I was never taught about this operator, and I would greatly appreciate any help regarding how to nest multiple comparisons within one line.
This is the code that I would like to shorten:
if(y<0)
y=0;
else
if(y+h>s.getHeight())
y = s.getHeight()-h;
I managed to condense each condition to this (not nested):
y = (y<0) ? 0 : y;
y = (y+h>s.getHeight()) ? s.getHeight()-h : y;
Is this the correct way to nest it?
y = (y<0) ? 0 : ((y+h>s.getHeight()) ? s.getHeight()-h : y);
Thank you!
EDIT: I was given a link to another post pertaining to the ?: operator. Link. However, my question has to do with nesting instead of just a simple if statement. Therefore, my question is not a duplicate of that post.
Yes, this is correct syntax but it's not readable.
You can check by yourself this in Java. Like this:
int a = 3;
int b = 5;
String s = (a < b) ? "Less than b" : (a > b) ? "More than b" : "Equal as b";
System.out.println(s);
But code is much more readable if you use if and if else statements. This ? and : is just for basic if statement.
For example:
int a = 3;
int b = 5;
String s = (a == b) ? "Equal" : "Not equal"
System.out.println(s);
But even in this case, I would rather use if statement. I really don't like to see ? and : instead of if statement :)
Regards,
golobic
You have correctly used ternary operator. However you could have avoided repeated method invocations for s.getHeight().
y = y < 0 ? 0 : y+h > s.getHeight() ? s.getHeight() - h : y;
Use the ?: (ternary) operator instead of an if-then-else statement if that makes code more readable.
ex. result = someCondition ? value1 : value2;
This can be nested further if value1, value2 are also ternary expressions.
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 10 years ago.
Possible Duplicate:
What is the Java ?: operator called and what does it do?
I am trying to read an implementation of a binary tree, and I ran across this one line of code:
if (...) {
...
} else {
node = ( node.left != null ) ? node.left : node.right; //this line
}
return node;
Can anyone tell me what this line means? My best guess is that it's a conditional statement of some kind.
It is called Conditional Operator.
In expression1 ? expression2: expression3, the expression1 returns a boolean value. If it is true then expression2 is evaluated, else expression3 is evaluated.
So in your code snippet: -
node = ( node.left != null ) ? node.left : node.right;
is equivalent to: -
if (node.left != null) {
node = node.left;
} else {
node = node.right;
}
This is known as the ternary operator, since in most languages it's the only operator which takes 3 arguments. It has the form:
a ? b : c
and evalutes to b if a is true, or c otherwise. It can be used almost anywhere, but most frequently it is used in assignment operations, since it becomes very difficult to read in more complex situations.
On a side note, "obfuscated" is not the right term here - that is meant for code which is deliberately rendered difficult to read. This might more accurately be called "obscure", although it is a common operator.
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