user3287300
user3287300

Reputation: 151

Executing a for loop after one is finished

I'm a beginner and I have a question on how loops work. Is there a type of loop where you can finish one loop then execute another loop after the first one is completely finished

for(int i = 0; i>array.length; i++) // Do this loop first
 {  
       Execute code
           .
           .
           .
 }

for(int i = 0; i>array.length; i++)  //Wait for the first one to finish now do this
 {  
       Execute code
           .
           .
           .
 }

Upvotes: 2

Views: 5269

Answers (4)

Mauno Vähä
Mauno Vähä

Reputation: 9788

Java code you write is by default synchronous meaning that any operation will block until it is completed. If it would be asynchronous - operation would only be triggered to be started while execution flow would move forward to next parts of the program. (In Java, this is usually done using separate threads).

Therefore, to keep it simple: your loops executes at same order as you write them.

As a final note: You probably wan't to know more about asynchronous operations later, don't get confused over them yet. Just know that those exists and can be used e.g., for long running background operations.

for(int i = 0; i < 5; i++){
    System.out.println("First loop: " + i);
}

for(int i = 0; i < 5; i++){
    System.out.println("Second loop: " + i);
}

Upvotes: 1

Hits Artkins
Hits Artkins

Reputation: 1

Assumptions:

  • Your code is not multithreaded
  • You want to execute one loop after the other without any kind of time delay.

Proceed as normal with any type of loop (for, while) one after the other.

for (int i = 0; i < someBound; i++) {
    // your first loop code here    
}

for (int i = 0; i < anotherBound; i++) {
    // your second loop code here
}

while (someCondition) {
    // your third loop code here
}
//... and so on for as many loops as you want

Hope this helps.

Upvotes: 0

user1767754
user1767754

Reputation: 25094

The code will run line by line, if a loop is not satisfied (become true), it will run over and over again. When finished, it will jump to the next statement

while (true){
// your code goes here
}

while (true){
// your code goes here
}

Upvotes: 0

nanofarad
nanofarad

Reputation: 41281

Yes. Just put one before the other:

for(int i = 0; i < array.length; i++){
    // loop1
}
for(int i = 0; i < anotherarray.length; i++){
    // loop2
}

Upvotes: 2

Related Questions