How to use 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.

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.

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

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



Leave a Reply

Trending Top 3 5G Smartphones