Java Loops Explained: for, while, do-while

🚀 Starting My Java Learning Journey – Day 6 🔹 Topic: Loops in Java Loops in Java are used to execute a block of code repeatedly until a certain condition is met. Java mainly provides three types of loops: 1️⃣ for Loop Used when the number of iterations is known. Example: public class Main { public static void main(String[] args) { for(int i = 1; i <= 5; i++) { System.out.println(i); } } } 2️⃣ while Loop Used when the number of iterations is not known beforehand. Example: public class Main { public static void main(String[] args) { int i = 1; while(i <= 5) { System.out.println(i); i++; } } } 3️⃣ do-while Loop The do-while loop executes the code at least once even if the condition is false. Example: public class Main { public static void main(String[] args) { int i = 1; do { System.out.println(i); i++; } while(i <= 5); } } 💡 Key Point: Loops help automate repetitive tasks and make programs more efficient. #Java #JavaLearning #Programming #BackendDevelopment #CodingJourney #JavaLoops

4. Enhanced for Loop (for-each) Best for iterating over arrays or collections — cleaner and less error-prone. int[] numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println(num); }

Like
Reply

To view or add a comment, sign in

Explore content categories