This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 6 years ago.
newTilt = (newTilt > 90) ? 90 : newTilt;
What does this line of code mean? It's the first time that I see something like this in Android.
This is the full method that contains the line above:
public void onTiltMore(View view) {
if (!checkReady()) {
return;
}
CameraPosition currentCameraPosition = mMap.getCameraPosition();
float currentTilt = currentCameraPosition.tilt;
float newTilt = currentTilt + 10;
newTilt = (newTilt > 90) ? 90 : newTilt;
CameraPosition cameraPosition = new CameraPosition.Builder(currentCameraPosition)
.tilt(newTilt).build();
changeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
It is a ternary expression. It says that if the newTilt at that point is above 90, it sets it to 90, otherwise it leaves it unchanged. You could kind of think of it in the way of an if-else statement.
if(newTilt > 90) {
newTilt = 90;
} else {
newtilt = newTilt; // which does nothing useful
}
This expression means that
newTilt = (newTilt > 90) ? 90 : newTilt;
is an expression which returns one of two values, 90 or newTilt. The condition, (newTilt > 90), is tested. If it is true the first value, 90 , is returned. If it is false, the second value, newTilt, is returned. Whichever value is returned is dependent on the conditional test, (newTilt > 90)
It's as someone has already said, it's called a ternary expression. It's something that you should really learn as I've seen it appear on quite a few interview questions. What this expression does, is if the expression evaluates to true then the left-side of the colon is used as the result and if it evaluates to false, then the right side is used. It's very often used as a shortcut to an if/else statement. In fact, you could write the above like this:
if (newTilt > 90)
newTilt = 90;
else
newTilt = newTilt;
Obviously, you don't need the else statement above, as newTilt doesn't change if it's less than 90. I'm just trying to show you how the ternary works.
In fact, a ternary is still a conditional expression.
int var = (expression) ? true value : false value;
Since the false condition actually does nothing, the above ternary would be better written as simply:
if (newTilt > 90)
newTilt = 90;
That's all you need.
Related
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
This question already has answers here:
Java logical operator short-circuiting
(10 answers)
Closed 7 years ago.
Will this code not evaluate the divide by zero portion of the if statement since the first part evaluates to false? If so, is this true for all cases in all Java IDEs? Or will certain compilers throw the exception?
int n = 0;
int x = 5;
if (n != 0 && x / n > 100) {
System.out.println(" s1");
} else {
System.out.println("s2");
}
From JLS §15.23:
The conditional-and operator && is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
So no, you will not get an exception.
Obviously this assumes that you have a single-threaded or thread safe environment - if you introduce visibility problems into the mix then it's anyone's guess.
Assuming we include the import for SoP, and that thoses lines are written inside a static main, there will be no exception thrown, and s2 will be printed.
X/0 will never be evaluated in your code because && check left expression first, thus, it will never throw anything.
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.
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
I know that one of them is bitwise and the other is logical but I can not figure this out:
Scanner sc = new Scanner(System.in);
System.out.println("Enter ur integer");
int x=sc.nextInt();
if(x=0)//Error...it can not be converted from int to boolean
System.out.println("...");
The error means that x cannot be converted to boolean or the result of x=0 can not be converted to boolean.
== checks for equality.
= is assignment.
What you're doing is:
if( x = Blah ) - in Java this statement is illegal as you can not test the state of an assignment statement. Specifically, Java does not treat assignment as a boolean operation, which is required in an if statement. This is in contrast with C/C++, which DOES allow you to treat assignment as a boolean operation, and can be the result of many hair-pulling bugs.
When you write 'x = 0' you are saying "Store 0 in the variable x". The return value on the whole expression is '0' (it's like this so you can say silly things like x = y = 0).
When you write 'x == 0' it says "Does x equal 0?". The return value on this expression is going to be either 'true' or 'false'.
In Java, you can't just say if(0) because if expects a true/false answer. So putting if(x = 0) is not correct, but if(x == 0) is fine.
== is a comparison operator, and = is assignment.
== is an equality check. if (x == 0) // if x equals 0
= is an assignment. x = 0; // the value of x is now 0
I know the question has been answered, but this still comes up from time to time not as a programmer error but as a typographical error (i.e., the programmer knew what he meant, but failed). It can be hard to see, since the two look so similar.
I've found that a way to help avoid doing this is to put the constant expression on the left-hand-side, like so:
if (0 == x)
...
That way, if I accidentally use only one "=" sign, the compiler will fail with an error about assigning to a constant expression, whether or not the assignment operator is left-associative and whether the if conditional expects a strongly-typed Boolean.
if(x=0)
Here you're assigning the value of 0 to the variable x. The if statement in Java can't evaluate an integer argument as it can in many other languages. In Java, if requires a boolean. Try
if(x == 0)
to do a comparison.
Interpret the error to mean
"The expression
x=0
cannot be converted to Boolean."
Just to clarify about C/C++ - assignment is evaluated to the right operand
if(a = n)
is evaluated to n, so (n = 1) is true (n = 0) is false
One interesting note: Since assignment operator evaluates to the right operand, the following is valid in Java(albeit not pretty):
if (( x = blah ) > 0) ...
Parenthesis are needed because of operator precedence ( '>' binds stronger than '=').
As others have already said, '=' is assignment; '==' is compare.
in your program change
if(x=0)
to
if(x==0)
"==" checks for equality
"=" Is used for assignment.
It is giving you error cause you're assigning value to x in if(), where you're supposed to check for the equality. Try changing it to equality instead of assignment operator.
As others stated, = assigns while == compares.
However, these statements have their own values as well.
The = operator returns the value of its right-hand operand. This is how statements like a = b = c = 5 work: they are parsed as a = (b = (c = 5)), which evaluates to a = (b = 5) and then a = 5.
The == operator returns a boolean that is true if its operands are equal. The if statement runs its body if its argument is true. Thus, if headers like if (5 == 5) translate to if (true). This is why sometimes you see infinite while loops with header while (true); the while loop runs "while" toe argument is true.
If you had a boolean in your if statement, it would give no error and run the code if the value being assigned (or "compared to") was true. This is why it is so important to never mix up the = and == operators, especially when working with booleans.
Hope this helped!!