• Profile
  • Resume
  • Portfolio
  • Blog
Avatar

Nelson Silva

A human. Being. Coffee lover.

Blog

I Write My Thoughts Here

break and continue in Java

March 2, 2022 Java

In this post, you will learn how to work with break and continue so that you can use that same knowledge and thus evolve.

  • break makes the life of the cycle come to an end, that is, makes it not iterate through anything else;
  • continue ignores the entire content of the loop that is following from itself and automatically moves to the next iteration.
package com.caffeinealgorithm.programminginjava;

import java.util.ArrayList;
import java.util.List;

public class BreakAndContinue {
  public void Run() {
    List<String> animals = new ArrayList<>();
    int counter = 0;

    animals.add("Dog");
    animals.add("Cat");
    animals.add("Chicken");
    animals.add("Rabbit");
    animals.add("Lion");

    for (String animal : animals) {
      System.out.printf("Animal: %s\n", animal);

      if (animal == "Chicken")
        break;
    }

    while (counter < 10) {
      counter++;

      if (counter == 5)
        continue;

      System.out.printf("Counter: %d\n", counter);
    }
  }
}

/*
  Animal: Dog
  Animal: Cat
  Animal: Chicken
  Counter: 1
  Counter: 2
  Counter: 3
  Counter: 4
  Counter: 6
  Counter: 7
  Counter: 8
  Counter: 9
  Counter: 10
*/

Don’t forget to watch the video and you can always read this post in Portuguese.

Happy coding!

Previous Next

Categories

  • Announcements
  • Python
  • C#
  • Java
  • Go

Latest Posts

  • for Loop in Go
    May 5, 2022
  • Switch in Go
    May 4, 2022
  • Comparison Operators in Go
    May 3, 2022
+351913416022
contact@nelsonsilvadev.com
Porto, Portugal
Nelson Silva © 2022 All Rights Reserved