This question already has answers here:
If statement executing all conditions
(9 answers)
Closed 4 years ago.
Got a basic if statement question, so I have an if statement in Java as shown here:
if (
!isOmitted(word,map.get(word.length()+1)) &&
!isInserted(word,map.get(word.length()-1)) &&
!isTransposed(word,map.get(word.length())) &&
!isSubstituted(word,map.get(word.length())) &&
!isCapital(word,map.get(word.length())))
{
noSuggestion=true;
}
where each individual method works perfectly as desired. Is there any way for java to check all conditions even when one is false? I know that the nature of the && operator is that as soon as a condition does not hold true, there is no point in checking the remaining conditions, as the entire condition is going to be set to false, but I was hoping I could do something like this in order to keep my code someone cleaner. I know I can use boolean variables, and assign the returned value to 5 different variables, but is there any other work around to force every condition to be checked? Thanks a lot in advanced
A single & is a non-short-circuit operand - ie both sides are evaluated irrespective of whether required.
More info here - https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22.2
However, this sounds like a poor design. In fact, some code analysis tools would automatically flag these operators as suspicious for this reason. Typically you would want to call each method as they make some change to the state of your objects, which is not something you would expect in an if statement. But your method names do not suggest this. What are you trying to achieve?
Related
This question already has answers here:
Java logical operator short-circuiting
(10 answers)
Closed yesterday.
Can somebody make an detailed explanation (and i mean really detailed, im dumb) of lazy evaluation in java and maybe also explain what is meant with eager evaluation?
Why is this bringing a runtime-error when b = 0?
if (a/b < 2 && b>0)//execute something
And why does this not give one?
if (b>0 && a/b < 2)//execute something
Both should be cases of lazy evaluation, but i just dont get why one is working and the other one isn't.
a/b < 2
gets a Division by zero error wich will be executed in the first example.
In the second example b>0 will be evaluated first , is false, so the second part will not be evaluated, because the first part is false and the complete result can't be true
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
OK, my first question in stackOverflow.
This is something that I left me completely baffled.
Java (I use android Studio), I write the following code:
Integer aNumber = 200;
String aNumberInString;
aNumberInString = Integer.toString(aNumber);
Boolean result;
if(aNumberInString == "200"){
result = true;
} else {
result = false;
}
Log.i("result:",result+"");
OK, logic and what I expect is that the condition is true... But NO! it fails.
I was really shocked by this behavior, then investigate a little more, and run the code in debug mode step by step.
when I get to the condition, I inspect the value of "aNumberInString" and to my surprise, this is what I find:
OK, so the first thing I think is: "Integer.toString ()" are doing something wrong.
Let's try another way: "String.valueOf ()"
Run in debug mode, and:
THE SAME! and fails, of course.
Obviously fails because it compares different characters, and in Internet I found a way to fix it,
string.replace ("\\ u0000", "");
but my question is not how to fix it, is:
Why is this happening?
Is there a correct way to prevent this from happening?
From already thank you very much to all,
Regards, Nicolas
You are doing a reference comparison. For comparing Strings, you need to call equals. By doing == with an Object, you are asking Java to make sure they are the same object, not if they have the same value.
Change:
if(aNumberInString == "200"){
To this:
if(aNumberInString.equals("200") {
Or better yet, to reduce the chance of a NullPointerExcpetion:
if("200".equals(aNumberInString))
This question already has answers here:
Semicolon at end of 'if' statement
(18 answers)
Closed 7 years ago.
Just a general Java question. Why does the null variable exist? I'm working with some introduction to CS students and one of the most common mistakes is semi-colons where they are not supposed to be. For example
if(isTired());{
sleep(10);
}
The misplaced semi-colon before the open parenthesis keeps the if statement from working correctly, and I was wondering why the null line did in a Java program. In this example null seems to be a detriment and was wondering when someone would use it when coding.
The null statement is useful because there are some places in Java where you want to do nothing. They are not frequent, but they exist. Often they are the 'compulsory' statements that you have to put in as part of a construct. For example, if you want to write a for loop that only terminates on a 'break', then you want there to be nothing in the 'conditional' part of the for:
for (int i=0;;i++) {
int j = complexCalculation(i);
if (j<0 && complexCondition(j)) {
break;
}
}
If the null statement wasn't allowed, that wouldn't compile. If it was allowed there, but not in other places, that would be inconsistent (and make life more difficult for compiler writers).
The reality is that, once you get to be fairly proficient with the language, errors caused by accidentally adding null statements are rare.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does Java evaluate remaining conditions after boolean result is known?
When executing code with multiple && statements in java, does the compiler continue to resolve additional boolean comparisons if the first one resolves to false?
if (1==2 && 3==4 && 4==5) { Do Something }
Once determining 1==2 is false, will the compiler immediately break out of the if statement or will it continue to resolve 3==4 and 4==5 after?
In the case of && it'll stop evaluating the moment it detects that one of the conditions is false. This is called short circuit evaluation.
"SHORT CIRCUIT EVALUATION IN PROGRAMMING LANGUAGES"
In the case of any logical expression most compiler stop evaluation expression as soon as result evaluated. its not only in Java but in almost in every language. (but not all e.g. VB6)
You can also check it as follows:
i = 0 , j =1;
i && ++j;
system.out.print(" j=" + j);
The value of j will be 1, it means ++j was not executed.
does the compiler continue to resolve additional boolean comparisons if the first one resolves to false
The short answer. No! The compiler javac and the JIT analyses statically all the code. It doesn't take short cuts like this. e.g. if the second condition doesn't compile, you will always get a compilation error regardless of the first condition.
What you may have intended to ask is; will the program execute the other conditions if the first or second one is false In this case, it will not.
This doesn't make a difference for the compiler -- all it does is resolve the boolean comparisons into machine code, represented by one or more .class files.
As far as the actual runtime... If I remember correctly from Computer Science class, both Tarun's and Lews's answers are correct -- the comparison will short-circuit as soon as it gets to an expression that isn't true.
IF "1==2" is false than the compiler will immediately break out the if statement.
&&
- The above is a short-circuit AND operator. If the 1st condition results in false the 2nd condition is not evaluated.
Eg:
if ((a==false) && (b==true)){
}
The above will stop after the first evaluation.
- If you want to force the evaluation of both the conditions, then try Non-Short Circuit AND (&)
A sidenote to the keyword 'Efficiency' in your title :- as stated by other answers your basic question is easily answered, so it's not a question of efficiency, but a question if you need for some reason all expressions to be evaluated, for example when executing code which changes state (which would be by the way not good coding at all).
But if you think of 'Efficiency' in terms of executing speed, then you almost never have to optimize on that level, either the compiler will do it for you or you wouldn't notice the difference. It may be important in some time critical operation or in operations which run in very big loops, but in nearly every other case, it's much more important to write clean code, so that another human can read it well.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why boolean in Java takes only true or false? Why not 1 or 0 also?
I was wondering today why Java cannot test any other type than a boolean.
In C, C++ and many other languages (actually most programming languages), the following is possible and valid:
int a = 0;
if (a) // evaluates to false
; // do something nice
a = 6;
if (a) // evaluates to true
; // do something more
This also works almost everywhere for objects, arrays; anything that can have a value of 0x00000000 in the memory.
The question: why is this not possible in Java (you have to keep on testing for == 0 or == null)?
I would guess that the rationale why is because it simplifies things.
An if statement has to evaluate a value to one of two possible conditions. What Java does is require you to supply a statement itself that must evaluate to two possible conditions (boolean) rather than accept other values and arbitrarily decide if that evaluates to true or false.
Because James Gosling et al decided that Java wouldn't do that.