Java do while, while - java

what behaviour can I expect when I run this code:
do while(testA) {
// do stuff
} while(testB);
Will it behave like:
do {
while(testA) {
// do stuff
}
} while(testB);
Or:
if(testA) {
do {
// do stuff
} while(testA && testB);
}
Or something totally unexpected?
I ask this question because I think this is quite ambiguous, and for other people searching on this topic, not because I am lazy to test it out.

It is equivalent to your first block:
do {
while(testA) {
// do stuff
}
} while(testB);
The relevant parts of the Java grammar when parsing this are:
DoStatement:
do Statement while ( Expression ) ;
Statement:
WhileStatement
WhileStatement:
while ( Expression ) Statement
Statement:
Block
Block:
{ BlockStatements_opt }
You can see that the Java compiler will parse this as do <WhileStatement> while ( Expression ) ;. That's the only valid way to parse the code that you wrote.
Keep in mind that it doesn't have any special rule to parse this construct. It just ends up being confusing for a human to read due to the unusual way the do-while loop is written. In normal usage do-while is always written as do { ... } while with explicit curly braces.

It works indeed, but the behaviour depends on what conditions your are testing. E.g. this code:
int i = 2;
int j = 4;
do while(j > 0) {
i--; j--;
System.out.println("i:" + i + " j:" + j);
} while(i > 0);
outputs:
i:1 j:3
i:0 j:2
i:-1 j:1
i:-2 j:0
So it works like:
while(j>0) {
}
Whereas by exchanging the variable names:
do while(i > 0) {
//.. same as above
} while(j > 0);
The output is:
i:1 j:3
i:0 j:2
It looks like it behaves the same as in the first case (i.e. the first while is considered), but here, the application is not terminating!
Summary:
At the time when testA is not satisfied anymore and testB is also not satisfied, the code works like a normal while(testA){} loop.
But: If, at the time when testA is no longer satisfied, testB is still satisfied, the loop is not executed any more and the script is not terminating. This only applies if the condition of the "outer" loop needs to be changed inside the loop.
Update:
And after reading other answer, I realize that this is exactly the behavior of the nested do-while - while loop.
Anyway, lesson learned: Don't use this kind of syntax because it can confuse you ;)

It behaves like
do {
while(testA) {
// stuff
}
} while(testB);
So, that block of code is parsed this way:
do {a block of code} while testB is true. Where {a block of code} is the inner while.
It's certainly a bit uncommon to write code like that :)

The answer is #1. It will continue to loop as long as testB is satisfied but it will not execute the code if testA is not satisfied.

"do {} while();" is one construct, while "while(){}" is another.
There is no such thing as "do while"; you are inadvertently nesting them and taking advantage of the fact that {} is optional for single instructions.
In other words, this is legal syntax:
do System.out.println("Hello World") while (true);
And like in if-statements, a block is treated as a single statement.
Which is to say, your first possible answer is the right one, where "while(){}" is the single non-bracketed thing inside the outer "do {} while();"

I do not think this code is legal.
do while(testA) {
// do stuff
} while(testB);

Related

if-statement with continue or break

I'm doing the simulation of Java OCA test. During my study with the book "OCA - Study Guide" (Sybex), at the second chapter there is the following (Table 2.5, page 91):
if - allows break statement: NO
if - allows continue statement: NO
But during the simulation of Java OCA test, did by Sybex (online book OCA), there is this question:
int x= 5;
while (x>=0) {
int y = 3;
while (y>0) {
if (x<2)
continue;
x--; y--;
System.out.println(x*y + " ");
}
}
My answer was: It doesn't compile
But the correct answer is:
8
3
0
2
What is the correct information?
What is right (book or simulation test)?
This is the table:
Thanks a lot!
I think what you need to understand is that in your code, the if statement is INSIDE a while loop (which is inside another while loop) and that's why it's OK to use continue in that case. An if statement outside of a loop isn't allowed to use continue. But inside of a for loop, while loop or do while loop, you CAN use continue inside an if statement.
So the code that you provided works and the output is:
8
3
0
2
But then I took your code and commented out the two while loops and now the code doesn't compile:
int x= 5;
// while (x>=0) {
int y = 3;
// while (y>0) {
if (x<2)
continue; //<-- COMPILE ERROR: continue cannot be used outside of a loop
x--; y--;
System.out.println(x*y + " ");
// }
// }
The output is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
continue cannot be used outside of a loop
I wrote a very detailed Java looping tutorial that covers the continue statement, the break statement, and all the different types of loops in Java.
i think continue here is following the outer while loop not immediate if , since continue is allowed inside while loop it works.
public static void main(String[] args) {
int x= 5;
//while (x>=0) {
int y = 3;
//while (y>0) {
if (x<2)
continue;
x--; y--;
System.out.println(x*y + " ");
}
}
// }
// }
Error:(10, 21) java: continue outside of loop
Both book and test simulators are right. break and continue keywords are not allowed inside if. The continue you see inside if is perfectly valid because it appears within the context of outer while so that's fine. To wrap it all, when you start a while or for block, using break and continue everywhere inside this block is correct, even if it happens to be inside an if block.
normally break and continue are allowed in if statements but you should not use them that often because it is bad Coding stlye.
*unit = unit test framework
A Reason would be for example: If you try to test your software with unit (if you dont know unit not yet dont worry :D) it is much harder to understand what the code does than normally and also to test the code.
Good Luck and have fun hope i can help you

Can all loops (for, while, do while) be expressed in terms of one another in java ?

I understand that we can express a do while loop in the form of a while loop and a while loop in the form of for loop. So the following conversions are possible (Correct me if I am wrong):
For -> While
While -> For
Do-While -> While
Do-While -> For
But I am not sure if I can convert a while loop to do while as while loop doesn't necessarily run atleast once. Is there a way around to convert a while loop to do-while?
You can easily go from while to do-while. For example, just add a boolean set to true at first, and in the loop condition, do like "condition OR boolean". Then in the loop, set your boolean to false. Here could be a way of doing it :
boolean condition = true;
while (condition) {
condition = doThings();
}
It's maybe not the best to do it, but it works perfectly only with adding a boolean variable.
EDIT : My bad, I corrected my answer. Now it is really a do-while loop.
I did another answer, which is more clear for me, I thing it really depends on your preferences. Here it is :
boolean bool = true;
while (yourCondition || bool) {
if (bool) {bool = false;}
}
For your curiosity, it happens (pretty much often I think) that compilers convert all types of loops into only one. So all loops are equivalent, you just need to find a way to do it :) .
Suppose you have an interface
interface LoopInfo {
Runnable init();
BooleanSupplier goOn();
Runnable next();
}
with a given instantiation
LoopInfo myInfo;
then this is a for-loop
for (myInfo.init().run(); myInfo.goOn(); myInfo.next().run()) {
// loop code
}
the equivalent while-do loop
myInfo.init().run();
while (myInfo.goOn()) {
// loop code
myInfo.next().run();
}
and the equivalent do-while loop
myInfo.init().run();
do {
if (myInfo.goOn()) {
// loop code
}
myInfo.next().run();
} while (myInfo.goOn());
So yes, they can be equivalently transferred between each other.

Why iteration of a block is prevented in java?

retry: {
.........
if(xyz < 5) {
continue retry;
}
}
Problem : continue cannot be used outside of a loop
Why iteration of a block is prevented in java?
It's not supported because noone implemented it, presumably because they thought that, well, loops should be implemented with the loop constructs Java provides.
What you want to do can easily be implemented as a while loop if you invert the condition and use break instead:
while (true) {
.........
if(xyz >= 5) {
break;
}
}
Or why not write it as a regular loop without break or continue?
do {
.........
} while (xyz < 5);
Problem : continue cannot be used outside of a loop
continue is used within a loop i.e. for/while/do-while, if statements are conditional code blocks and not loops.
Learn more about code branching statements here:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
The purpose of continue keyword is to skip rest of the code inside loop to start with the next pass of loop. So, by it's purpose, continue would not fit in the contexts outside the loops.
goto could be other option for you to reset (or restart) the code of execution. However the best way could be move such part into a method and use recursion along with return under specific conditions to achieve the purpose you are talking about.
As others have pointed out, labels in Java label loops, and are used to specify which loop to break or continue.
That said, if you really want to write "spaghetti code" you can misuse break and continue like for instance:
public class SillyGotoExmple {
public static void main(String args[]) {
int count, loops;
final int NUM_LOOPS=2;
final int MAX_COUNT=10;
loops=0;
bar: do {
count = 0;
foo: do {
System.out.println(count);
if(++count < MAX_COUNT) {
continue foo;
} else if(++loops < NUM_LOOPS) {
continue bar;
} else {
break bar;
}
} while (true);
} while(true);
}
}
For some more discussion on goto in Java, see e.g. Is there a goto statement in Java?

Java: infinite loop after an if inside a loop

So I have a loop that is wrapped around a loop and an if statement. When running the program however, it gets out of the inner loop (as planned) and then it fails the if statement (also as planned), resorting to the else statement which is a simple print.
What I /wanted/ to happen was have it then (in the case the if fails), restart to the original inner loop--hence the outer loop. But instead, after it fails the if statement, it begins to loop "phrase2" over and over.
Here is the simplified code:
int x = 1;
int y = 1;
int i = 0;
while(i == 0)
{
while(<condition that is false>)
{
System.out.println("phrase1");
a = input.nextInt();
b = input.nextInt();
}
if(<condition that is false>)
{
i = 1;
}
else
{
System.out.println("phrase2");
}
}
Thanks for your help regardless!
EDIT:
For the sake of emphasis...
What happens:
Infinite loop spewing "phrase2".
What I wanted:
After the else is executed, I wanted to be brought into the inner loop again.
Whatever condition you're using in the inner loop, just make sure it's true.
else
{
System.out.println("phrase2");
// SET THIS TO TRUE: <condition that is false>
}
This way, the inner loop will trigger again.
Your control never enters the below if statement
if(<condition that is false>)
{
i = 1;
}
You might need to adjust your conditions so that it comes into the above if block. Introduce a System.out.println inside if statement to debug
It looks like you have some code that you probably want to run once, unless something went wrong, and then you want to go back and retry. The idiom I usually use for that looks like
boolean needToRetry;
do {
needToRetry = false;
// do whatever
if (somethingWentWrong) {
needToRetry = true;
// set this at any point where you find you will need to go back
}
} while (needToRetry);
The important thing is that you need to reset your flag (needToRetry) at the beginning of the loop, each time. (P.S. There are other ways to do this using break or continue, although I personally don't like using continue.)

When would a do-while loop be the better than a while-loop?

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.

Categories

Resources