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
Related
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?
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 8 years ago.
This function is supposed to take two parameters, however there are characters included that I do not understand what they mean. What is the value of "?". What are the two parameters in this function, I know panel.id is one of them . any link to a library that explain them well ? thank you
setPanelType(panel.id, ((encType) ? PANEL_ST_ENC : PANEL_NORMAL))
The duplicate question posted here might be explaining what the "?" operator is. However I was not sure if it is used differently in a function parameter call. This question is not a duplicate of any.
You've run in to something called the "conditional operator"*. It's basically a short way of writing an if-statement.
For example:
String var;
var = 1 > 0 ? "It's bigger than 0" : "It's 0 or smaller";
Is the same as:
String var;
if(1 > 0){
var = "It's bigger than 0";
}else{
var = "It's 0 or smaller";
}
* It's also sometimes called the "ternary" operator, but that's not quite correct. It's a "ternary operator" (an operator that accepts three operands, just like the multiplication operator * is a binary operator because it accepts two operands), but in theory there could be others. In fact, I think it's the only ternary operator in Java or JavaScript (at least for now).
This syntax is shorthand for a conditional action in Javascript.
(condition) ? (true action) : (false action)
Related: JavaScript ternary operator example with functions
The '?' means Ternary Operator as said above, encType is a boolean variable.
setPanelType(panel.id, ((encType) ? PANEL_ST_ENC : PANEL_NORMAL))
is equals to:
if (encType)
setPanelType(panel.id, PANEL_ST_ENC))
else
setPanelType(panel.id, PANEL_NORMAL))
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.
This question already has answers here:
Which is more effective: if (null == variable) or if (variable == null)? [duplicate]
(9 answers)
Closed 4 years ago.
Possible Duplicate:
Order of condition checking?
When i read some source codes, the if statement is coded in this way,
if (1 == a) {
...
}
instead of
if (a == 1){
...
}
I read a programming book about the advantage of this way, but cannot remember exactly what it is about. Any one know about this ?
(Sorry if this question disturbs you :-) )
The advantage is compiler will tell you that error right away. For example, a = 1 will compile but will produce an error at run time whereas 1 = a will produce an error at compile time since 1 is not a valid lvalue.
Example: this will produce an error right away:
int a = 0;
if(1 = a) {
print("test");
}
Whereas this will compile (warnings may be produced depending on the compiler) but it will cause issues at run time.
int a = 0;
if(a = 1) {
print("test");
}
The main idea here is to make certain that you are using == in a condition instead of =.
That being said every modern compiler (ie. Eclipse) will treat the above as an error now. So it's not as big of a deal as it used to back in the notepad and vi days (in my opinion). I personally prefer the a == 1 since that seems more readable to me.
In classic C, where a condition is an integral expression, it's very easy to write
if (a = 1)
by mistake. The problem is that if you do it, the compiler won't complain, since the assignment evaluates to an integer, too. Writing the expression backward makes it such that if you make this typo, the code won't compile. It's not a bad idea to do this in C; it makes much less sense in other languages.
If you leave out an =, 1 = a is a compiler error, whereas a = 1 is a subtle mistake.