If you have code like this:
if (A > X && B > Y)
{
Action1();
}
else if(A > X || B > Y)
{
Action2();
}
With A > X and B > Y, will both parts of the if-else-if ladder be executed?
I'm dealing with Java code where this is present. I normally work in C++, but am an extremely new (and sporadic) programmer in both languages.
No, they won't both execute. It goes in order of how you've written them, and logically this makes sense; Even though the second one reads 'else if', you can still think of it as 'else'.
Consider a typical if/else block:
if(true){
// Blah
} else{
// Blah blah
}
If your first statement is true, you don't even bother looking at what needs to be done in the else case, because it is irrelevant. Similarly, if you have 'if/elseif', you won't waste your time looking at succeeding blocks because the first one is true.
A real world example could be assigning grades. You might try something like this:
if(grade > 90){
// Student gets A
} else if(grade > 80){
// Student gets B
} else if(grade > 70){
// Student gets c
}
If the student got a 99%, all of these conditions are true. However, you're not going to assign the student A, B and C.
That's why order is important. If I executed this code, and put the B block before the A block, you would assign that same student with a B instead of an A, because the A block wouldn't be executed.
If both A > X and B > Y are true then your code will only execute Action1. If one of the conditions is true it will execute Action2. If none are true, it will do nothing.
Using this:
if (A > X || B > Y) {
Action2
if (A > X && B > Y) {
Action1
}
}
will result in the possibility of both actions occurring when A > X and B > Y are both true.
If you're talking about C, then only the first block that satisfies the condition is executed - after the control "enters" the conditional block it then "leaves" after all other conditions.
If you want such behavior, then just use two separate conditions - remove "else" and you have it.
When the condition after if is true, only the first block is executed. The else block is only executed when the condition is false. It doesn't matter what's in the else block, it's not executed. The fact that the else block is another if statement is irrelevant; it won't be executed, so it will never perform the (A > X || B > X) test, and its body will not be executed even if that condition is true.
Related
This question already has answers here:
What is the benefit of terminating if … else if constructs with an else clause?
(13 answers)
Closed 6 years ago.
I was thinking the other day about the creation of "else-if" statements and why the way of its execution causes each event to be guaranteed mutually exclusive.
For example:
if(condition A)
//condition
else if(condition B)
//will run if condition A is false and condition B is true
else if(condition C)
//will run if condition A is false and condition B is false and condition C is true
else if(condition D)
//will run if all the above conditions are false and condition D is true.
I would think it would make more sense for all the "else" statements to be checked if condition A is not true, and not just stop if either B or C are true. My intuition thinks it would be more natural to have the above code be equivalent to this:
if(condition A)
//condition
else {
if(condition B)
//...
if(condition C)
//...
if(condition D)
//...
}
So therefore, why do we define else-if the way we do? Is it to circumvent unnecessary nesting of if-else statements? I just think it is ambiguous and would make sense to have it be equivalent to my second code snippet.
Edit: to clear up confusion, I completely understand that these two statements are not always equivalent. My question is primarily asking why else-if is defined such that the first statement is not always equivalent to the second statement? I'm trying to understand why else-if runs the way it does.
Edit 2: I think I finally understand the underlying essence of my question. Generally, "else" checks if the above statement is false, and if it is, it runs the statement. However, in the case of elif, it checks to see if all the above statements are false before running. This is different from the duplicate question as it asks about the nature of if-else itself, rather than its exhaustiveness.
EDIT 3: I have opened a new question which is hopefully clearer, found here.
The reason one would prefer one style over the other is to ensure either the presence or lack of mutual exclusion when testing the conditions.
If it is the case that Condition B, C, or D are not mutually exclusive with one another, then...
...in the first scenario, only Condition B would fire, due to the mutual exclusivity of the else if statement.
...in the second scenario, Conditions B, C, and D would fire, due to the fact that they are not mutually exclusive due to the if statement.
Ultimately it depends on what you want to do. You may want to run multiple statements in this fashion. However, you probably don't. Fashioning your statements in a mutually exclusive way ensures that you don't run into strange logical bugs when you get a result or state that you didn't expect.
If you take your nesting approach, and apply it consistently, you would actually come up with this:
if (condition A) {
// A
} else {
if (condition B) {
// B
} else {
if (condition C) {
// C
} else {
if (condition D) {
// D
}
}
}
}
Each if gets treated the same way. The first if statement doesn't have any special ability to remove the else block from all the other if statements. The grammar you suggest gives else an inconsistent meaning.
Let's take a basic example.
Assume, You want to award a grade according to the score of the student and score is 60.
if(score <= 50) {
System.out.println("C Grade");
} else if(score <= 70) {
System.out.println("B Grade");
} else if(score <= 100) {
System.out.println("A Grade");
}
It will print B Grade.
if(score<=50) {
System.out.println("C Grade");
} else {
if(score <= 70) {
System.out.println("B Grade");
}
if(score <= 100) {
System.out.println("A Grade");
}
}
Now, According to you if we follow above approach where conditions are not mutually exclusive. It will print B Grade and A Grade which is not true.
So, in the cases where conditions in if are not mutually exclusive you will run into problems. That's why nesting of if..else is needed.
This is a highly subjective question, so I'll be more specific. Is there any time that a do-while loop would be a better style of coding than a normal while-loop?
e.g.
int count = 0;
do {
System.out.println("Welcome to Java");
count++;
} while (count < 10);`
It doesn't seem to make sense to me to check the while condition after evaluating the do-statement (aka forcing the do statement to run at least once).
For something simple like my above example, I would imagine that:
int count = 0;
while(count < 10) {
System.out.println("Welcome to Java"); count++;
}
would be generally considered to have been written in a better writing style.
Can anyone provide me a working example of when a do-while loop would be considered the only/best option? Do you have a do-while loop in your code? What role does it play and why did you opt for the do-while loop?
(I've got an inkling feeling that the do-while loop may be of use in coding games. Correct me, game developers, if I am wrong!)
If you want to read data from a network socket until a character sequence is found, you first need to read the data and then check the data for the escape sequence.
do
{
// read data
} while ( /* data is not escape sequence */ );
The while statement continually executes a block of statements while a particular condition is true
while (expression) {
statement(s)
}
do-while evaluates its expression at the bottom of the loop, and therefore, the statements within the do block are always executed at least once.
do {
statement(s)
} while (expression);
Now will talk about functional difference,
while-loops consist of a conditional branch instructions such as if_icmpge or if_icmplt and a goto statement. The conditional instruction branches the execution to the instruction immediately after the loop and therefore terminates the loop if the condition is not met. The final instruction in the loop is a goto that branches the byte code back to the beginning of the loop ensuring the byte code keeps looping until the conditional branch is met.
A Do-while-loops are also very similar to for-loops and while-loops except that they do not require the goto instruction as the conditional branch is the last instruction and is be used to loop back to the beginning
A do-while loop always runs the loop body at least once - it skips the initial condition check. Since it skips first check, one branch will be less and one less condition to be evaluated.
By using do-while you may gain performance if the expression/condition is complex, since it is ensured to loop atleast once. In that casedo-while could call for performance gain
Very Impressive findings here,
http://blog.jamesdbloom.com/JavaCodeToByteCode_PartOne.html#while_loop
The do-while loop is basically an inverted version of the while-loop.
It executes the loop statements unconditionally the first time.
It then evaluates the conditional expression specified before executing the statements again.
int sum = 0;
int i = 0;
do
{
sum += ids[i];
i++;
} while (i < 4);
Reference material
Simply, when you want to check condition before and then perform operation while is better option, and if you want to perform operation at least once and then check the condition do-while is better.
As per your question a working example,
1. when I needed to find the field which could be declared in the same class or the super class or the super class of that super class and so on i.e. finding the field located in deep class hierarchy. (A extends B B extends C and so on)
public Field SearchFieldInHierarchy(Object classObj, String fieldName )
{
Field type = null;
Class clz = classObj.getClass();
do
{
try
{
type = clz.getDeclaredField(fieldName);
break;
} catch (NoSuchFieldException e)
{
clz = clz.getSuperclass();
}
} while(clz != null || clz != Object.class);
return type;
}
2. When reading input stream from Http response
do
{
bytesRead = inputStream.read(buffer, totalBytesRead, buffer.length - totalBytesRead);
totalBytesRead += bytesRead;
} while (totalBytesRead < buffer.length && bytesRead != 0);
You kind of answer the question yourself-when it needs to run at least once, and it makes sense to read it that way.
do - while loop allows you to ensure that the piece of code is executed at least once before it goes into the iteration.
In a while loop, the condition is tested before it executes code in the loop. In a do while loop, the code is executed before the condition is tested, resulting in the code always being executed at least once. Example:
$value = 5;
while($value > 10){
echo "Value is greater than 10";
}
The above would never output anything. If we do the same again like this:
$value = 5;
do{
echo "Value is greater than 10";
}while($value > 10)
It would output Value is greater than 10 because the condition is tested after the loop is executed. After this it would not output anything further.
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.
For example do check this link: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
If the looping condition can only be known after a first step of the loop (when you do not want a condition before you enter the loop).
Typically:
do {
expr = ...;
while (expr);
Use the while Statement when you have to check a condition repeatedly and only when the condition is satisfied execute the loop
while(condition) //eg. a>5
{
Body of Loop
}
If you see the flow of control here you can see that the condition is checked before the execution of the loop, if the condition is not met the loop will not execute at all
In the Do-While statement the program will execute the body of the loop once and then it will check if the statement is true or not
do
{
Body of Loop
}
while(condition); //eg. a>5
If you notice the flow of control here you will see that the body is executed once, then the condition is checked. If the condition is False the Program will break out of the loop, if True it will continue executing till the condition is not satisfied
It is to be noted that while and do-while give the same output only the flow of control is different
/*
while loop
5 bucks
1 chocolate = 1 bucks
while my money is greater than 1 bucks
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1
end
come to home and cant go to while shop because my money = 0 bucks
*/
#include<stdio.h>
int main(){
int money = 5;
while( money >= 1){
printf("inside the shopk and selecting chocolate\n");
printf("after selecting chocolate paying 1 bucks\n");
money = money - 1 ;
printf("my remaining moeny = %d\n", money);
printf("\n\n");
}
printf("dont have money cant go inside the shop, money = %d", money);
return 0;
}
infinite money
while( codition ){ // condition will always true ....infinite loop
statement(s)
}
please visit this video for better understanding
https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s
It is very simple to distinguish between the two. Let's take While loop first.
The syntax of while loop is as follows:
// expression value is available, and its value "matter".
// if true, while block will never be executed.
while(expression) {
// When inside while block, statements are executed, and
// expression is again evaluated to check the condition.
// If the condition is true, the while block is again iterated
// else it exists the while block.
}
Now, let's take the do-while loop.
The syntax of do-while is different:
// expression value is available but "doesn't matter" before this loop, & the
// control starts executing the while block.
do {
// statements are executed, and the
// statements is evaluated and to check the condition. If true
// the while block is iterated, else it exits.
} while(expression);
A sample program is given below to make this concept clear:
public class WhileAndDoWhile {
public static void main(String args[]) {
int i = 10;
System.out.println("While");
while (i >= 1) {
System.out.println(i);
i--;
}
// Here i is already 0, not >= 1.
System.out.println("do-while");
do {
System.out.println(i);
i--;
} while (i >= 1);
}
}
Compile and run this program, and the difference becomes apparent.
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.
I'm making a game where there is a goalie. i want him to move back and forth forever. i have an int called goalieposx (goalie position on the x axis) and i want this is go up by 1 until it hits 200, then go down by one till its back a 0 and repeat. I've tried the folllowing
//this bit isnt in the method, its outside as global varibale
boolean forward=true
//this bit is in a method which is continiouly called nonstop
if (goalieposx<200){
forward=true;
}
else if (goalieposx>200){
forward=false;
}
System.out.println(forward);
if(forward=true){
goalieposx++;
System.out.println("forward");
}
else if (forward=false){
goalieposx--;
System.out.println("backwards");
}
}
this method is called continously. It prints true until it gets to 200, then it prints false. However, it always prints forward, never backward. So conclusion is: the boolean changes as expected but the first if is always called, it seems to ignore the condition
ive also tried this
if(forward = true){
if(goalieposx==200){
forward=false;
}
else{
goalieposx++;}
}
else{
if(goalieposx==0){
forward=true;
}
else{
goalieposx--;}
System.out.println(goalieposx);
}
but this doesnt work either, it prints 1 then 2 etc upto 200 then prints 200 forever. Anyone know how i can solve this? is an if statement the wrong idea altogether?
This is why you should never do comparison for boolean types in if, while, for, whatever. You have just done the assignment in your if statement:
if(forward=true)
the above if statement will always evaluate to true. The problem with this is, this compiles successfully in Java, as syntax wise it's alright. Compiler just checks the type of expression in if evaluates to boolean or not. And it does, so it's ok with it.
You need to do the comparison:
if(forward==true)
.. but as I said, you should not do comparison for boolean types. So, simply doing this:
if(forward)
would be enough.
You also don't need those else if in both the conditions. Just an else will work fine. Well, I don't understand the use of boolean variable at all. It seems like you don't need it. You can change your code to:
if (goalieposx<200){
// forward=true;
goalieposx++;
System.out.println("forward");
}
else {
// forward=false;
goalieposx--;
System.out.println("backwards");
}
What you were previously doing is, setting a boolean variable, based on a condition, and using that boolean variable as condition to execute another if-else block. Well, whatever you are executing in the 2nd if-else block, can simply be moved in the original if-else block, without taking the help of the middle-actor boolean variable.
if(forward=true) does not do what you thing it does.
In java = is the assignment operator and == is the comparison operator. What you are doing with that statement is saying "if assign forward to true" which will set forward to true and always return true.
What you mean to say is if(forward) and if(!forward).
In fact you don't need the else if just an else as if the boolean is not true it must be false.
A better way to do it is to get it to move to the left by adding a minus number, and to the right by adding a positive number. Here's an example of doing this with a loop:
for(int i = -10; i < 100; i++) {
xPosition += i;
}
This would add -10 then -9 etc. to the position.
In your if statements, you need to put two equal signs to check for equality.
if (forward == true){
// execute code
}
EDIT 1:
if (forward)
would be much simpler.
First let's examine what you have already written:
if (goalieposx<200){
forward=true;
}
else if (goalieposx>200){
forward=false;
}
The problem with this code being first is that it while it might set the direction to false once 'goalieposx' has reached 201, in the next call, it will set the direction back to true.
Instead, try using this clever alternative:
//This goes before the infinite loop method
counter = 0;
//Then in the infinite loop method
counter++;
if(counter > 100) {
counter = -100;
}
goalieposx = 100 + counter; //(this shifts counter from
// between -100 and 100 to 0 and 200)
The problem is you are setting the direction based on the value of the integer, instead of whether a condition has previously been met. Try this:
//this bit is in a method which is continiouly called nonstop
if (forward && (goalieposx>200)){
forward=false;
}
System.out.println(forward);
if(forward=true){
goalieposx++;
System.out.println("forward");
}
else if (forward=false){
goalieposx--;
System.out.println("backwards");
}
}
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.