In Java, if I use a ternary if operator inside a regular if, for example:
if ((x > y - z) ? true : callLongWaitedMethod(many, parameteres)) {
loveTeddyBear();
}
will it execute the callLongWaitedMethod if x > y - z is indeed true? I hope it is not and I can use this nice statement, slightly complicated at the first glance, but more attractive to compare with the extra boolean variable:
boolean b = (x > y - z) ? true : callLongWaitedMethod(many, parameteres);
if (b) {
loveTeddyBear();
}
especially if I'm using this inside a big loop which iterates over and over, so creating boolean each time will not be nice from the performance point of view while if I declare the boolean outside the loop, I may miss the neat because of the big size of the loop.
This will work as you hope, but it would be clearer to simply use the normal || operator to accomplish exactly the same result:
if ((x > y - z) || callLongWaitedMethod(many, parameteres)) {
loveTeddyBear();
}
According to the Java Language Specification 15.25, the long method will only be evaluated if necessary:
The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.
callLongWaitedMethod will not be called if x > y - z is true.
If you want to execute callLongWaitedMethod when (x > y - z) is true you actually have to swap the expression:
if ((x > y - z) ? callLongWaitedMethod(many, parameteres) : true ) {
loveTeddyBear();
}
It seems like you have the answer you want. You could also just use debugging statements with a simple version of your code to see what gets executed as a way of verifying the behavior. Something like
if ((1 > 2) ? true : someSimpleMethod()) {
System.out.println("true if");
}
And as your someSimpleMethod() have
public boolean someSimpleMethod() {
System.out.println("calling someSimpleMethod()");
return true;
}
From there you can swap 1 and 2 to see if the someSimpleMethod() would execute.
You should ask yourself as the coder, if you can't figure out what it's going to do, should you really be coding it that way? why not just this:
if ( (x>y-z) ||
(x<=y-z && callLongWaitedMethod(many, parameteres))) {
loveTeddyBear();
}
This will make much more sense to the novice programmer who is not familiar with your code.
Related
I usually code python, but decided to try to learn a new language (Java). I am a complete beginner with around 2 hours of experience. In python, we can use "or" so that if one condition is satisfied it executes the block of code.EG:
if x>y or 10<12:
print("one of these is true")
is there an equivalent for this in java ?
I quess
if( x > y || 10 < 12) {
System.out.println("one of these is true");
}
should do the thing.
This solution will work for you.
if (x>y || 10<12) {
print("one of these is true");
}
The equivalent if-statement would be
if (x > y || 10 < 12) {
....
}
Alternatively you can just skip that, since 10 < 12 will always evaluate to true.
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.
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.
Which is better in terms of best practice / efficiency?
if (x == 1
&& y == 1
&& z == 1)
{ do things }
or
if (x != 1 ||
y != 1 ||
z != 1)
{ don't do things and go to a different bit of logic.}
Is there any difference in efficiency when short circuiting ANDs and ORs? Is it (generally) better to check positively or negatively when multiple logical assertions need to be made?
For pure optimization of the code it depends case-by-case. The scenario that will on average do the least amount of comparisons.
For code design it is also case-by-case. The if-cases should match what you are actually looking for. A function that tests if a string is inputted correctly for example. (the tests are made up)
public boolean isValidString (string s) {
if (s.isEmpty())
return false;
if (s.length() < 12)
return false;
if (s...)
return false
return true;
}
In this case the most logical approach is the ||. It could be written.
public boolean isValidString (string s) {
if (s.isEmpty() || s.length() < 12 || s...)
return false;
return true;
}
With http://en.wikipedia.org/wiki/De_Morgan%27s_laws this could be rewritten to not and. However it is not what we want to test, even though they yield the same result.
So stick to the logical approach in general cases.
If you think about efficiency then think about how often each case will occur. The most likely one should be put in front so the whole expression is shortcircuited immediately.
Better you use "==" instead of going for "!=".
This is also recommended with PMD.
The following is good and improves redability.
If(true){
//
}else{
//
}
than
If(!true){
//
}else{
//
}
Well, in some JVM implementations boolean values are stored as integers in the JVM. int value 1 meaning true and int value 0 meaning false. Also, comparison logic at processor level is architecture dependent. Some machines might subtract 2 operands, then add and then compare, others might compare byte by byte etc.. So, unless you are looking at a specific hardware architecture (which you shouldn't.. atleast for java programming language), I don't think this matters much..
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;
}