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;
}
Related
This question already has answers here:
"Comparison method violates its general contract!"
(13 answers)
Closed 1 year ago.
I have defined a Comparator using the ordering wrapper. Could you explain why does this code throw an exception, "Comparison method violates its general contract!"? I would really appreciate it if you could tell me how to fix it.
Ordering<Foo> order = new Ordering<Foo>() {
#Override
public int compare(Foo left, Foo right) {
return getCompare(orderMap, left.getItemId(), right.getItemId());
}
};
Collections.sort(Foos, order);
getCompare :
private int getCompare(Map<Long, Integer> orderMap, Long leftId, Long rightId) {
int indexLeft = orderMap.get(leftId) == null ? -1 : orderMap.get(leftId);
int indexRight = orderMap.get(leftId) == null ? -1 : orderMap.get(rightId);
if (indexLeft < 0 || indexRight < 0) {
return 1;
}
return Integer.compare(indexLeft, indexRight);
}
This is the contract:
If `a.compare(b) is X, and b.compare(c) is X, then a.compare(c) must also be X, whether X is negative, or positive, or zero.
If a.compare(b) is X, then b.compare(a) must be -X: 0 remains 0, -1 turns to +1, etc.
a.compare(a) must be 0.
That's it. Your compare method breaks this in many, many ways. For example, your second line has a bug in it(surely that'd be orderMap.get(rightId) == null, you can clean that up using getOrDefault instead), if either index is not found or less than 0, your code always returns 1, which breaks the rule (a.compare(b), where a is not in the map, returns 1, and b.compare(a) would also return 1. It needs to return a negative number instead).
You're going to have to come up with a rule for what happens if one of these is not in the map. If your code is written with the assumption it can't happen, well, it is - throw an exception when your assumption doesn't hold so you can investigate why your assumption (that all provided left/rightIds are always in the map and always non-negative). As written, your code straight up asplodes in a nasty way if that happens - that's what exceptions are for. Explode in an easily debuggable way.
If that was the intent, you're going to have to make up some rules. For example: If a is in the map but b is not, then a is always higher than b. That means if (indexLeft < 0 && indexRight >= 0) return -1 and also if (indexLeft >= 0 && indexRight < 0) return +1;, in order to stick to the rules. That leaves the question: What if neither is in. You can either choose that there is then no way to order them (Return 0), but do know that means you can't put more than once such item in a TreeMap or TreeSet - but sorting a list, that's fine. Individually not-comparables are allowed, and they'll end up clumped together in an arbitrary order. That doesn't break the rules.
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 really don't know what should be the title of this question, spent 10 minutes but this is the best I came up with.
The real question is very basic and I think I know the answer. But still, like the operator condition ? true-statement : false-statement, is there any shortcut of this kind of if statement?
if(intA == -1 || intB == -1 || intC == -1 || intD == -1 || intE == -1)
Suggestion: Something like this could be added in Java:
if((intA || intB || intC || intD || intE) == -1)
No.. There isn't. These are different variables with different values.
Suggestion: you can consider the all these variable necessary or not. If all these variables necessary there will be no way to simplify.
You should use lists for this purpose.
For ex.
You can implement function
findFirstEquals(List, Int)
which iterate through the list, search for first element that equals to second parameter and returns true if found.
In this case your if would be like following
intList = ArrayList<Int>()
// put 5, 6, 7,8 etc...
if findFirstEquals(intList, -1) ...
Afaik, there is no real shortcut syntax for this. Probably, you could do some tricks with logical and/or to achieve this, but I would not recommend to do so as it would be harder to read:
if (((intA | intB | intC) & -1) == -1)
You could still add those ints to an collection, and check if -1 is contained in that collection.
Fun fact: In Python, there is syntactic sugar for comparing a variable with 2 values; you can write 2 < a < 3, which would not be possible in Java. But personally, I do not know a language where syntactic sugar for what you are asking for exists.
You can use Switch() statement to make it more easy like below
public void myMethod(int intValue)
{
switch (intValue) {
case -1: //Your logic here ;
break;
case 1 : //Another condition
break;
default: //Default behaviour;
break;
}
}
Call method myMethod(yourValue) and passed your value to it.
Passed your integer value to switch it will handle it as per value you have passed.
May this will help you.
Ok, i am building program to check many fields. If at least 1 field is not ok then i don't want my program to spend time to check other fields. So let look at this code:
// Util.isReadyToUse method return true if the string is ready for using, & return false if it is not.
boolean isOK=true;
if(!Util.isReadyToUse(firstName)){
isOK=false;
}
else if(isOK && !Util.isReadyToUse(lastName)){
isOK=false;
}
else if(isOK && !Util.isReadyToUse(email)){
isOK=false;
}
.....more checking
if(isOK) {
//do sthing
}
Ok, when running, the program will first check !Util.isReadyToUse(firstName). Suppose it returns (isOK=false). Next the program will check isOK && !Util.isReadyToUse(lastName).
So my question here is that Since the isOK currently false, then will the program spend time to check the condition !Util.isReadyToUse(lastName) after &&?
Ok, As a human being, if you see isOK=false and now you see isOK && !Util.isReadyToUse(email), then you don't want to waste time to look at !Util.isReadyToUse(email) since isOK=false and u saw && after isOK.
Will machine also work like that?
I am thinking to use break but why people say break doesn't work in if statement:
if(!Util.isReadyToUse(firstName)){
isOK=false;
break;
}
else if(isOK && !Util.isReadyToUse(lastName)){
isOK=false;
break;
}......
What is the best solution in this situation?
So my question here is that Since the isOK currently false, then will
the program spend time to check the condition
!Util.isReadyToUse(lastName) after &&?
Java is smart, if you have a condition if(somethingFlase && something), then something won't be reached due to Short-circuit evaluation. Since the whole expression will be false regardless of the second condition, there is no need for Java to evaluate that.
From 15.23. Conditional-And Operator &&:
If the resulting value is false, the value of the conditional-and
expression is false and the right-hand operand expression is not
evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated.
if(a && b) - if a is false, b won't be checked.
if(a && b) - if a is true, b will be checked, because if it's false, the expression will be false.
if(a || b) - if a is true, b won't be checked, because this is true anyway.
if(a || b) - if a is false, b will be checked, because if b is true then it'll be true.
No, it shortcuts the rest of the predicate.
That's you'll see things like
if(A != null && A.SomeVal == someOtherVal)
Java supports what is referred to as Short-Circuit Evaluation. See this page:
http://en.wikipedia.org/wiki/Short-circuit_evaluation
What this means is that if the first boolean in your statement is enough to satisfy the statement, then the rest of the values are skipped. If we have the following:
boolean a = false;
boolean b = true;
if(a && b) /*Do something*/;
'b' will never be checked, because the false value for 'a' was enough to break out of the if statement.
That being said, your program will never take advantage of this because the only time isOK is set to false is within one of your else if statements.
As the other responders mentioned Java will do the smart thing.
But it could be the case that you want Java to continue to check, in that case you can use & vs && or | vs ||.
if (someMethod() | anotherMethod() {
If the first method reutrns true, Java will still execute the second method.
if (someMethod() & anotherMethod() {
If the first method is false, Java will still execute the second method.
No, Java won't "waste time" for it. It's called short circuit evaluation.
This mechanism is commonly used e.g. for null checking :
if (foo != null && foo.neverFailsWithNPE()) {
// ...
}
You don't need to use break on an if..else if.. else statement because once it finds a condition which is true the rest aren't even looked at.
Let's take a simple example of an object Cat. I want to be sure the "not null" cat is either orange or grey.
if(cat != null && cat.getColor() == "orange" || cat.getColor() == "grey") {
//do stuff
}
I believe AND comes first, then the OR. I'm kinda fuzzy though, so here are my questions:
Can someone walk me through this statement so I'm sure I get what happens?
Also, what happens if I add parentheses; does that change the order of operations?
Will my order of operations change from language to language?
The Java Tutorials has a list illustrating operator precedence. The equality operators will be evaluated first, then &&, then ||. Parentheses will be evaluated before anything else, so adding them can change the order. This is usually pretty much the same from language to language, but it's always a good idea to double check.
It's the small variations in behavior that you're not expecting that can cause you to spend an entire day debugging, so it's a good idea to put the parentheses in place so you're sure what the order of evaluation will be.
Boolean order of operations (in all languages I believe):
parens
NOT
AND
OR
So your logic above is equivalent to:
(cat != null && cat.getColor() == "orange") || cat.getColor() == "grey"
The expression is basically identical to:
if ( (cat != null && cat.getColor() == "orange") || cat.getColor() == "grey") {
...
}
The order of precedence here is that AND (&&) has higher precedence than OR (||).
You should also know that using == to test for String equality will sometimes work in Java but it is not how you should do it. You should do:
if (cat != null && ("orange".equals(cat.getColor()) || "grey".equals(cat.getColor()))) {
...
}
ie use the equals() methods for String comparison, not == which simply does reference equality. Reference equality for strings can be misleading. For example:
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false
First, your if statement contains three main expressions:
cat != null
cat.getColor() == "orange"
cat.getColor() == "grey"
The first expression simply checks whether cat is not null. Its necessary otherwise the the second expression will get executed and will result in a NPE(null pointer excpetion). That's why the use of && between the first and second expression. When you use &&, if the first expression evaluates to false the second expression is never executed.
Finally you check whether the cat's color is grey.
Finally note that your if statement is
still wrong because if cat is
null, the third expression is still
executed and hence you get a null
pointer exception.
The right way of doing it is:
if(cat != null && (cat.getColor() == "orange" || cat.getColor() == "grey")) {
//do stuff
}
Check the order of parenthesis.
Yeah && is definitely evaluated before ||. But I see you are doing cat.getColor() == "orange" which might give you unexpected result. You may want to this instead :
if(cat != null && ("orange".equals(cat.getColor()) || "grey".equals(cat.getColor()))) {
//do stuff
}
Order of Operation is not what you need, you need boolean algebra, this includes boolean functions. Maxterms/minterms, Gray code, Karnaugh tables, diodes,transistors, logic gates, multiplexers, bitadders, flip flops...
What you want is to implement boolean "logic" on computers or virtual machines. With "order of operations" you may refer something about physics like managing delays on logic gates (OR, if) nanoseconds intervals?