Incomplete for loop in Java - java

I've started to learn java, and in some examples I've seen special for loop (not very familiar to me). It's not enhanced for loop, but it looks like this
for(;;i++){ do something..}
I don't know what it means, when I just have these semicolons o.O If someone could explain it to me, would be grateful.

I would read through this: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
As you might notice,
The general form of the for statement can be expressed as follows:
for (initialization; termination;
increment) {
statement(s)
}
...
The three expressions of the for loop are optional; an infinite loop can be created as follows:
// infinite loop
for ( ; ; ) {
// your code goes here
}
(emphasis mine)
In your example, I would expect the variable i would have been declared and initialized before the for loop. If there is no termination condition, the loop will run infinitely.
You can also have a termination condition inside a loop, something like :
if(i = some number) {break;} //this will break the loop
Similarly, the increment statement can also be declared inside a loop.

Related

Having issue with the concept of extra semi-colon at the end of for loop in Java

I was writing a code to insert an element at the end of the linked list. However without using the semi-colon at the end of for, I'm unable to get the list updated properly, what is the significance of this semi-colon and how is this affecting my code?
public void insertAtEnd() throws IOException {
LinkedList node=new LinkedList();
System.out.println("Enter an element");
int value=Integer.parseInt(br.readLine());
node.setData(value);
LinkedList p,q;
for(p=head; (q=p.getNext())!=null; p=q);
p.setNext(node);
}
The semicolon means that the statement below won't be executed until the loop has exited. Your case, the loop is taking p to the end of the list (the last element) and then the next statement is assigning its next value to the new element
Well, the way it is constructed right now as for(p=head; (q=p.getNext())!=null; p=q);, the for loop has an empty body. The variables p and q through the p.getNext() and p=q assignments are updating. Then it is executing the p.setNext(node); a single time.
EDIT: As to why the code is working with the semi-colon, it is because you are advancing the variables p and q over the list. While the for loop with the empty body is fine, I think traditionally one sees a while loop.
The indentation of the p.setNode(node); makes it appear as if the statement were related to the for loop, but it really isn't, as the goal is to find the end of the linked list by iterating over it.
(note: others made similar points while I was typing this answer)
it needs to be removed, it is causing it to do nothing in the loop.
The loop will execute the next single block of code after the loop. Either one statement, or one { } code block.
In this case, you have one statement ;, so it "executes" and does nothing, and then will call your p.setNext(node); after the loop ends.
public void insertAtEnd() throws IOException {
LinkedList node=new LinkedList();
System.out.println("Enter an element");
int value=Integer.parseInt(br.readLine());
node.setData(value);
LinkedList p,q;
for(p=head; (q=p.getNext())!=null; p=q)
p.setNext(node);
}
The semicolon is essentially transforming what you appear to want to do because of your indentation:
for(p=head; (q=p.getNext())!=null; p=q)
{
p.setNext(node);
}
into the following:
for(p=head; (q=p.getNext())!=null; p=q)
{
}
p.setNext(node);
So with the semicolon your loop is executing nothing at every iteration. Then, after it has finished executing, you're running p.setNext(node); exactly once.
Usually you can avoid this problem in the future by explicitly writing your curly braces as I have done in these two code segments. It is unclear exactly which code segment you are trying to accomplish right now.
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
//statement(s)
}
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once,
as the loop begin
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
In your case, the loop is taking p to the end of the list (the last element) and then the next statement is assigning its next value to the new element

Initialization statement

I'm reading a Java book and I came across an interesting for loop. It looks like this:
for(; (j>0) && (tmp < a[j-1]); j--)
I understand that (j>0) && (tmp < a[j-1]) is the condition check and j-- is the decrease of the variable. However, I don't get where's the initialization statement.
There is no initialization statement in your example. It's optional.
j is probably declared and initialized before the loop.
Normally, you would initialize j in the first statement in the for loop (which is empty here) since it is a looping index and is usually only used inside the loop. Also the standard syntax for Java for loops is for( initialization; termination condition; increment), but the language only enforces that there be three statements (with the middle one being a boolean expression) , so you can have three empty statements for(;;) which creates an infinite loop or you could put some other statement in there (except for the middle expression where a boolean expression is expected) like for(System.out.println("I was supposed to initialize here"); false && true; logger.log("Nope.")). OF course, you shouldn't do that, but it is legal.
Note: Some statements would be illegal if put in place of the third statement as well, like variable declarations, since it is executed at the end of each iteration (see this for more on legal for loop syntax)
I like to think of for loops as a shorthand for a common form of the while loop, where you want to loop a number of times:
int i= 0; // Initialization
while (i< max){ // termination
// Do stuff
i++; // increment
}
which is helpful for understanding what it does with these statements.
for(initialization; condition; increment)
None of them are a must to declare a for loop. You can have a for loop like for(;;) if you want. It will compile without any errors.
According to your question j have been already initialized some where. Therefore it is perfectly fine.

Post initialising a local variable in Java

I was about to post a query but I solved it by reworking the code avoiding the issue but not answering it.
So below is an example of what I was wanting to do.
I had a for loop inside a do-while loop and wanted the do-while loop to run until a condition relating to the nested for loop was reached. The error I was getting was that i wasn't initialised so the while condition could not be run, which makes sense.
I was hoping to create a local variable outside the do-while loop and initialize it in the nested for loop. This obviously wasn't possible in the way I was trying to execute it but is there another way to 'post initialise' a variable in Java?
Also just out of curiosity what languages allow such post initialisation?
case 2:
int i;
do{
try{
for(i=0; i<array.length;i++){
if(...
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
} while(!array[i].state.equals("X"));
break;
You can easily solve it by giving i an initial value when you declare it :
int i = 0;
You have to initialize de variable i before the do-while.
Inside the do-while loop you can reset the variable. Now you've already made it in the for condition.
On the other hand, I don't know what your code inside for made it and the logic of your algorithm, but I think that it's possible you have a infinite loop if there aren't any element with the state "X". I think that it is very posible indeed (of course depends of your algorithm) to remove the for loop and add the code in the do-while with a i++ and an end condition like this: while(!array[i].state.equals("X") && i < array.lengh);

Does the break statement break out of loops or only out of if statements?

In the following code, does the break statement break out of the if statement only or out of the for loop too?
I need it to break out of the loop too.
for (int i = 0; i < 5; i++) {
if (i == temp)
// do something
else {
temp = i;
break;
}
}
That would break out of the for loop. In fact break only makes sense when talking about loops, since they break from the loop entirely, while continue only goes to the next iteration.
An unlabelled break only breaks out of the enclosing switch, for, while or do-while construct. It does not take if statements into account.
See http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html for more details.
It also goes out of the loop.
You can also use labeled breaks that can break out of outer loops (and arbitrary code blocks).
looplbl: for(int i=;i<;i++){
if (i == temp)
// do something
else {
temp = i;
break looplbl;
}
}
It breaks the loop, but why not explicitly put the condition in the for itself? It would be more readable and you would not have to write the if statement at all
(if i==temp then temp = i is totally pointless)
It will break out of the loop always.
Break never refers to if/else statements. It only refers to loops (if/while) and switch statements.
break is to break out of any loop.
Generally break statement breaks out of loops (for, while, and do...while) and switch statements.
In Java there are 2 variant of break.
1. Labeled break
It break outs of the outer loop where you put the lable.
breakThis: for(...){
for(...){
...
break breakThis; // breaks the outer for loop
}
}
2. Unlabeled break
It is the statement you used in your question.
It breaks the loop in which it is written. Generally inner loop.
It would break you out of the for loop. Generally break statement is used to optimise the running time of your program. Means when the given condition is met, use break statement so that it will take you out of the loop and ignores the remaining iterations.

While Loop Weirdness in Java

I noticed that java (hence probably C) has no problem with this:
while(condition1) {
//do somethin'
} while(condition2);
Is this the same as:
while(condition1 && condition2) {
//do somethin'
}
No, you have two loops.
while(condition1) {
// do something
}
while(condition2); // second loop which does nothing.
The second loop is the same as
while(condition2) { }
EDIT: My suggestion is to use the automatic formatter in your IDE regularly. Otherwise you can create formatting which suggests the code does things it doesn't.
example 1
if (condition)
statement1;
statement2;
statement3;
In this example, it appears that the first two statements are part of the if condition, but only the first is.
example 2
http://www.google.com/
statement;
Doesn't look like legal Java, but it is, not for the reasons the formatting suggests ;)
No, they are different.
The first while(condition1) will run first.
Then comes while(condition2), which has nothing after it except a single ; which means it's just some empty statement.
Remember that in control blocks like if, for, while, if you don't use the {} braces, then only the first immediate statement after it will be considered part of it.
Example:
if (condition)
System.out.println("hello"); // prints only if condition is true.
System.out.println("no"); // not bound to the 'if'. Prints regardless.
while (condition)
; // do nothing!
System.out.println("something"); // not bound to the while
Edit The empty while loop is mentioned in the Java code conventions
7.6 while Statements
A while statement should have the following form:
while (condition) {
statements;
}
An empty while statement should have the following form:
while (condition);
There is no construct is java as shown in the first form. You have probably seen
do {
} while (cond)
EDIT : You are misreading the first form. There should have been a line break after the }. This confused me as well.

Categories