Java: What is "for (;;)" [duplicate] - java

This question already has answers here:
How does a for loop work, specifically for(;;)?
(6 answers)
Closed 6 years ago.
Would any one please explain this instruction for me:
for (;;)
I have encountered several kinds of these mark (like in ajax code of facebook and in concurrent stuff of Java).

An infinite loop.
Each of the three parts of a for loop (for(x; y; z)) is optional.
So you can do this:
int i = 0;
for (; i < 20; ++i)
and it's perfectly valid, or
for (int i = 0; i < 20;) { ++i; }
or
for (int i = 0; ; ++i) { if (i < 20) { break; } }
and they're all valid.
You can also omit all three parts, with for(;;). Then you have a loop that:
does no initialization (the first part)
has no condition for stopping (the middle part)
does nothing after each iteration (the last part)
so basically an endless loop. It just does what it says in the loop body, again and again

It's an endless loop. For the specificion of the for statement, see here.

That's an infinite loop, similar to
while(true)
{
...
}

Its an infinite loop, seeing as the (non-existent) exit condition will never be false.
Any for loop without an exit condition will be infinite:
for (int x=0; ; x++) { }
Exactly the same as while (true), although a little less readable IMHO.

The syntax for a for loop is
for (init-stmt; condition; next-stmt) {
}
So it is simply a for loop with no initial statement, next statement or condition. The absence of the exiting condition makes it infinite.

That's indeed an infinite loop. But in Java you should really prefer while (true) over for (;;) since it's more readable (which you probably already realize). The compiler will optimize it anyway. In JavaScript there's no means of a compiler and every byte over HTTP counts, that's the reason why for (;;) is preferred. It saves a few characters (bytes).

Related

Why this loop is endless

I am new to programming.
I was doing a homework, and I got a question about this code:
do {
int i=4;
} while (true);
Why is this loop endless?
It's one of the most basic things in programming - the while loop. The while loop keeps executing as long as its condition is truthy. So, since the condition in your code is true, it will run forever because there's nothing else to stop the loop.
Hopefully this will help you understand it:
var condition = true;
var i = 5;
do{
i--; // decrement the value of i
console.log('i is now', i);
if (i == 0)
condition = false;
} while (condition);
console.log('loop ended');
See it here: http://jsfiddle.net/9cr0yqp6/
you have not exit method. you never set the loop to false.
This is an infinite loop because you do not have a condition to exit the loop.
True will always be true so the loop continues to execute until your condition is false (which cannot happen).
This loop while infinitely create a local variable named i and then assign the value 4 to it.
This is Java, not JavaScript.
Loops continue to loop when the condition remains true.
Example of a loop that ends and an explanation why:
for(var i = 0; i < 5; i++) {
//do something
}
Each iteration i increases by 1 (due to i++), and once the condition (being i < 5) is no longer true, the loop breaks out and ends.
In your loop, true will always be true.
Perhaps to explain why the loop is endless, let's look at one that ends:
var i = 4;
do{
i = i + 1;
} while (i < 6);
This loop will iterate while it turns i to 5, then 6, and that will make the condition in the while statement false, which ends the loop.
If you have while (true) instead, the condition will never be false, and the loop never ends.
The "while" loop is endless because you set the condition to true.

About labels in Java behaving like GOTOs

Shouldn't this loop infinitely?
someLabel:{
for (int i = 0; i < 5; ++i) {
System.out.println(i);
if (i == 3)
break someLabel;
}
}
It goes
0
1
2
3
Then dies. I was reading a question about an alternative to GOTO in Java. This was the accepted answer: https://stackoverflow.com/a/2430789/555690. Shouldn't the for loop be executed again?
From http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html:
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.
Apart from the fact that I never saw any real code using this kind of control flow, I guess a use for it would be to break an outer loop from an inner loop (as described in the provided link):
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
The Java language specification states
A break statement with label Identifier attempts to transfer control
to the enclosing labeled statement (ยง14.7) that has the same
Identifier as its label; this statement, which is called the break
target, then immediately completes normally.
The statement here is actually a block statement. Once you break, that block ends.
So, no, the for loop should not iterate again since it's inside the block that just ended.

Modify while loop to execute at-least once

doing some exam revision. One question is, Modifiy code to so that the loop will execute at-least once.
My Code :
int x = 0;
while (x < 10) {
if (x % 2 != 0) {
System.out.println(x);
}
x++;
}
Now i know while will loop while the condition is true, i know i cannot remove the x++ as this will give me infinite zeros. i think i would just remove the if statement and the brace related to it.
would you agree?
int x = 0;
while (x < 10) {
System.out.println(x);
x++;
}
Although this specific loop actually executes at least once even unchanged, that is not a property of a while-loop.
If the condition in the while-loop is not met, the loop never executes.
A do-while loop works almost the same way, except the condition is evaluated after execution of the loop, hence, the loop always executes at least once:
void Foo(bool someCondition)
{
while (someCondition)
{
// code here is never executed if someCondition is FALSE
}
}
on the other hand:
void Foo(bool someCondition)
{
do
{
// code here is executed whatever the value of someCondition
}
while (someCondition) // but the loop is only executed *again* if someCondition is TRUE
}
I would not agree, that would change the fundamental purpose of the loop (to emit every other number to stdout).
Look into converting to the do/while loop.
Whilst your solution has technically answered the question, I don't think it's what they were looking for (which isn't really your fault, and makes it a badly-worded question in my opinion). Given it's an exam question, I think what they're after here is a do while loop.
It works the same as a while loop except that the while condition is checked at the end of the loop - which means that it will always execute at least once.
Example:
while(condition){
foo();
}
Here, condition is checked first, and then if condition is true, the loop is executed, and foo() is called.
Whereas here:
do{
foo();
}while(condition)
the loop is executed once, foo() is called, and then condition is checked to know whether to execute the loop again.
More:
For further reading you might want to check out this or this tutorial on while, do while and for loops.
int x = 0;
while (x <10){
System.out.println(x);
x++;
}
Will work
EDIT: i think the others comments are rights too, the do/while loop will force one execution of the code
var x = 0;
do {
if (x % 2 != 0) System.out.println(x);
x++;
} while (x < 10);

Java Android For statement/loop parameters

Hello i've aquired some java code from an android sample project online and in the code there is a For statement/loop. The parameters for this For statement are displayed as (;;) rather than something like (int i = 0; i < string; i++). Can anyone explain exactly what this loop is doing by having the parameters as (;;)? i've tried researching online but can't find a thing!
thanks
for (;;) {
len = mSerial.read(rbuf);
rbuf[len] = 0;
if (len > 0) {
//do something
}
}
for (;;)
is an infinite for loop as there is no exit condition.
For loop syntax
for(initialization; Boolean_expression; update)
{
//body
}
initialization,Boolean_expression,update, body: all of them are optional. The for loop keep executing until Boolean_expression till it is not false. If Boolean_expression is missing then for loop will never terminate.
no initialisation, no exit condition, no increment.. it is a infinite loop?
It is an infinite loop. A for loop has 4 parts
for (initialisation; condition; increment/decrement) {
loop body
}
You may choose to omit any of these parts (although some compilers may complain about the lack of a loop body and others will omit the entire loop for performance).
It is perfectly feasible that you may already have a variable initialised, and may skip the initialisation within the loop:
int i = 0;
for ( ; i < 10; i++ ) {
// do something
}
It is also possible that you can choose to omit the incrementation, and do it elsewhere (be careful to include it inside the loop, otherwise this may lead to infinite loops unintentionally):
for ( int i = 0; i < 10; ) {
// do something
i++;
}
It is also possible to omit the conditional and include that elsewhere:
for ( int i = 0; ; i++ ) {
// do something
if (i == 9) {
break;
}
}
Or you can omit all of it entirely and make an infinite loop.
It is an infinite loop that does something when the if condition is satisfied. It can be used if you are waiting for an input from the user untill then it loops foreever.
When you declare for loop for (;;) .Every time loop will check the condition always it will return true so it goes in infinite loop.it is similar to while(true).if you want to break the loop then yo need to add break statement then it will come out from infinite loop.

what does "do" do here? (java)

I saw this bit of code on the interents somewhere. I'm wondering what the do is for.
public class LoopControl {
public static void main(String[] args) {
int count = 0;
do {
if (count % 2 == 0) {
for (int j = 0; j < count; j++) {
System.out.print(j+1);
if (j < count-1) {
System.out.print(", ");
}
}
System.out.println();
}
count++;
}
while (count <= 5);
}
}
By which I mean what exactly does do mean? What's its function? Any other information would be useful, too.
It is a do-while loop. So it will do everything in the following block while count is less than or equal to 5. The difference between this and a normal while loop is that the condition is evaluated at the end of the loop not the start. So the loop is guarenteed to execute at least once.
Sun tutorial on while and do-while.
Oh, and in this case it will print:
1, 2
1, 2, 3, 4
Edit: just so you know there will also be a new line at the start, but the formatting doesn't seem to let me show that.
It is similar to a while loop, with the only difference being that it is executed at least once.
Why? Because the while condition is only evaluated after the do block.
Why is it useful? Consider, for example, a game menu. First, you want to show the menu (the do block), and then, you want to keep showing the menu until someone chooses the exit option, which would be the while stop condition.
It's a while loop that gets executed at least once.
Edit: The while and do-while Statements
do { ... } while(CONDITION) ensures that the block inside do will be executed at least once even if the condition is not satisfied, on the other hand a while statment will never execute if the condition is not met
It goes with the while. do { ... } while() is a loop that has the conditon in the end.

Categories