Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Loop Do-While | Loops
Principios Básicos de Java
course content

Contenido del Curso

Principios Básicos de Java

Principios Básicos de Java

1. Iniciando
2. Tipos Básicos, Operaciones
3. Loops
4. Arrays
5. String

book
Loop Do-While

What is the difference between while and do-while?

The do-while loop is another type of loop in Java that is similar to the while loop. However, it has one important difference: the condition is checked at the end of each iteration. This means the code block will always execute at least once before evaluating the condition.

Here's the basic syntax of the do-while loop:

java

Main

copy
123
do { // Code block } while (condition);

Here are some key points to keep in mind about the do-while loop:

  • Execution Flow: The code block is executed first, and then the condition is checked. If the condition is true, the loop continues to the next iteration. If the condition is false, the loop terminates, and the program continues with the next statement after the loop;

  • Guaranteed Execution: Since the code block is executed before the condition check, the do-while loop is useful when you want to ensure that the code block runs at least once, regardless of the initial condition;

  • Variable Scope: Variables defined within the code block of a do-while loop have a scope limited to that code block. They cannot be accessed outside the loop;

  • Use Cases: The do-while loop is commonly used when you want to prompt the user for input at least once and then continue the loop based on a condition. It is also useful when iterating through a list of elements, ensuring that the loop runs at least once, even if it is empty.

Let's look at a simple example of usage and compare the results of a while loop and a do-while loop on a very basic example:

java

main

copy
12345678910
package com.example; public class Main { public static void main(String[] args) { // do-while loop do { System.out.println("Do-while loop executed successfully"); } while (1 < 0); } }

Veamos un ejemplo sencillo de uso y comparemos los resultados de un loop while y un loop do-while en un ejemplo muy básico:

java

main

copy
1234567891011
package com.example; public class Main { public static void main(String[] args) { // do-while loop do { System.out.println("Do-while loop executed successfully"); } while (1 < 0); } }

bucle while:

1. What will be the output of the code?

2. What will be the output of the code?

What will be the output of the code?

What will be the output of the code?

Selecciona la respuesta correcta

What will be the output of the code?

What will be the output of the code?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 3
We're sorry to hear that something went wrong. What happened?
some-alt