📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In Java, for loops are fundamental control structures used to iterate over a range of values. Sometimes, it's necessary to know when you're on the last iteration of a for loop, perhaps to handle a special case or to avoid adding a separator in a string builder scenario.
While Java's for loop doesn't provide a built-in way to identify the last iteration, there are several techniques you can use to detect it. In this blog post, we'll explore how to find the last iteration of a for loop in Java.
Method 1: Using a Counter Variable
One common method is to use a counter variable and compare it with the total number of iterations.
Example:
public class ForLoopLastIteration { public static void main(String[] args) { String[] items = {"apple", "banana", "cherry", "date"}; int totalItems = items.length; for (int i = 0; i < totalItems; i++) { System.out.print(items[i]); if (i < totalItems - 1) { System.out.print(", "); } else { System.out.println(" - Last Item!"); } } } }
Output:
apple, banana, cherry, date - Last Item!
Method 2: Using a Flag Variable
Example:
public class ForLoopLastIteration { public static void main(String[] args) { String[] items = {"apple", "banana", "cherry", "date"}; boolean isLastIteration; for (int i = 0; i < items.length; i++) { isLastIteration = (i == items.length - 1); System.out.print(items[i]); if (!isLastIteration) { System.out.print(", "); } else { System.out.println(" - Last Item!"); } } } }
Output:
apple, banana, cherry, date - Last Item!
Method 3: Using the Enhanced For Loop
Example:
public class ForLoopLastIteration { public static void main(String[] args) { String[] items = {"apple", "banana", "cherry", "date"}; int counter = 0; int totalItems = items.length; for (String item : items) { System.out.print(item); if (counter < totalItems - 1) { System.out.print(", "); } else { System.out.println(" - Last Item!"); } counter++; } } }
Output:
apple, banana, cherry, date - Last Item!
Comments
Post a Comment
Leave Comment