Java statements: Obfuscated code - `?:` [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?
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.

Related

How java test conditions [duplicate]

This question already has answers here:
Does Java evaluate remaining conditions after boolean result is known?
(7 answers)
Closed 7 years ago.
Does java calculate the second condition in ( test1 || test2 ) if the first one is true ?
I use Optional and I have something like that :
if (!opt.isPresent() || opt.get() == currentPlayer.getSelectedRegion())
and there will be a problem if the first test is true and java compute the second test.
If first condition is true second condition is not evaluated.
If first condition is false also second condition is evaluated.
That's why you can write a code like the following without a NullPointerException
if (str == null || str.length() == 0) {
// do something
}
The operator | (instead of || ) will evaluated both conditions
So the code
if (str == null | str.length() == 0) {
// do something
}
can generate a NullPointerException if str is null
Does java calculate the second condition in ( test1 || test2 ) if the first one is true ?
No. Boolean or will short-circuit, the first true is sufficient to make the expression true. No further conditions will be evaluated after that.
If you use the || and &&, rather than the | and &, Java will not bother to evaluate the right-hand operand.
No, java short-cut operators, the second argument is not evaluated if the first is. Ore more formal:
for x || y, y is only evaluated if x is false; and
for x && y, x is only evaluated if y is true.
This will increase performance and can be both useful and tricky:
usefull: to prevent you from doing things such that an error is thrown. The most typical example is the null check:
if(x != null && x.someTest())
this will prevent .someTest being called if x is null.
tricky: the problematic aspect can be if you call a method that does not only return something, but changes state as well. For instance:
public class Foo {
private int checked = 0;
bool someCondition () {
return (checked % 2) == 0;
}
bool neverChecked () {
checked++;
return checked == 1;
}
}
if you now call:
if(foo.someCondition() || foo.neverChecked());
this is one of the main reasons it is adviseable to keep "getters" (thinks that calculate things of an object), and "setters" (things that modify the state of an object), clearly separated. From the moment you start mixing, one can get complicated behavior in some circumstances.
it can be the intention that you always increment checked, but it will only if .someCondition happens to be false.

Is there any way to force java to test two condition regardless the first condition? [duplicate]

This question already has answers here:
Is there a way to disable short circuit evaluation in Java?
(3 answers)
Closed 8 years ago.
let's say I have a statement
if(stack.pop() == 1 && stack.pop() == 1)
if top of stack is 0, then the second condition won't be implemented, which means it just pops one value at the top. What I want is to pop both, the top and the value after top. Is there any way to do that without using another if-else statement in it?
int first = stack.pop();
int second = stack.pop();
if (first == 1 && second == 1)
Use the bitwise AND operator**:
if( stack.pop() == 1 & stack.pop() == 1 )
This will force the evaluation of both sides.
** I know it by "non-short-circuiting" of logical AND, but it is indeed a bitwise operator that acts on boolean operands (documentation here).
Update: As JBNizet said in his comment below, this code is "fragile", since some developer may "correct" the operator to the short-circuit version. If you choose to use & instead of storing the values of the method calls (forcing them to run) likewise JBNizet answer, you should write a comment before your if statement.
Yet another one-line and slightly obfuscated way to do this:
if( stack.pop() == 1 ? stack.pop() == 1 : stack.pop() == 1 && false )
Personally I'd go for JB Nizet's way. Makes it as clear as can be exactly what you're trying to do.
easiest, I found is (if stack only contains 0 and 1):
if(stack.pop() + stack.pop() == 2)
or JB's solution with one variable:
int first = stack.pop();
if (stack.pop() == 1 && first == 1)
Here is an approach that will bypass the EmptyStackException thrown when the stack has fewer than two elements.
if (stack.size() > 0) {
int first = stack.pop();
if (stack.size() > 0) {
if (first == 1 && stack.pop() == 1) ; //do something here
}
}

explain this line of code android

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.

Evaluation of && boolean operator

If i have the following if statement
if ( (row != -1) && (array[row][col] != 10) ) {
....
}
Where row is an int value and array is an int[][] object.
My question is, if this will throw an exception if row = -1 as the array won't have a -1 field, so out of bounds exception? Or will it stop at the first part of the if, the (row!=-1) and because that is false, it will ignore the rest?
Or to be sure it doesn't throw exception, i should separate the above if statement into two?
(Pls, don't tell me to check this out for my self :) I'm asking here 'cause i wanna ask a followup question as well ...)
It will stop safely before throwing an exception
The && is a short-circuiting boolean operator, which means that it will stop execution of the expression as soon as one part returns false (since this means that the entire expression must be false).
Note that it also guaranteed to evaluate the parts of the expression in order, so it is safe to use in situations such as these.
It will not throw an exception. However, if row is < -1 (-2 for example), then you're going to run into problems.
It will stop at the first part of the if. Java uses short circuite evaluation.
No, It wont. the compiler will not check the second expression if the first expression is false... That is why && is called "short circuit" operator...
Called a short-circuit evaluation via the && and if the row check fails, there is no point in continuing evaluation.
Most programming languages short-circuit the test when the first expression returns false for an AND test and true for an OR test. In your case, the AND test will be short-circuited and no exception will occur.
Many programming languages have short-circuit evaluation for logical operators.
In a statement such as A and B, the language will evaluate A first. If A is false, then the entire expression is false; it doesn't matter whether B is true or false.
In your case, when row is equal to -1, row != -1 will be false, and the short-circui the array expression won't be evaluated.
Also, your second question about the behavior of the array index is entirely language-dependent. In C, array[n] means *(array + n). In python, array[-1] gives you the last item in the array. In C++, you might have an array with an overloaded [] operator that accepts negative indexes as well. In Java, you'll get an ArrayIndexOutOfBoundsException.
Also, you might need something like the following (or just use a try/catch).
boolean isItSafe(int[][] a, int x, int y) {
boolean isSafe = true;
if (a == null || a.length == 0 || x >= a.length || x < 0 || y < 0 || y >= a[0].length ) {
isSafe = false;
}
return isSafe;
}

Another way of writing If statement in java [duplicate]

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

Categories

Resources