How to use for loop in Java ?

Using for loop in Java

Hey there,

Lets consider a scenario where in you need to repeat the some functionality over a similar elements / objects in Java. In order to achieve this we need to create a list of similar elements and visit each one of those to use some functionality. Let’s take an example below.

#Scenario :
I know few programming languages and want to print the name of those.

#Solution:
I will create a list of programming languages (at here List of Strings i.e. similar elements of type String) and then I will loop through each element in the list to print.

#Steps:
1. Create a List of String type

List<String> programingLanguages = new ArrayList<>(); //Define List of type ArrayList class

2. Add elements in the List

programingLanguages.add("C++"); //Add values to the List
programingLanguages.add("C#");
programingLanguages.add("Java");
programingLanguages.add("Python");
programingLanguages.add("Go");

3. Loop through each element in the List using for loop
4. Call System.out.print method to print out each element in a single line

for (String programingLanguage : programingLanguages) { //for loop to print each element in List
    System.out.println(programingLanguage); // Calling println method to print each element
}

#output:

C++
C#
Java
Python
Go

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.