Java for-each Loop

Java for-each Loop:

We can use the Eclipse IDE for this example. If you do not know about it then follow this link- How to Install Eclipse For Java and create a program in it.

The for-each loop is used to traverse the array or collection in java. It is easier to use than simple for loop because we don’t need to increment value and use subscript notation. It works on the basis of an element, not an index. It returns elements one by one in the defined variable.

Syntax of Java for-each Loop:

for (Type var : array) {
//code to be executed
}

Example 1: Printing Array using for-each loop.

for each loop java codeunit
public class For_each_loop {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String [] subjects = {"computer","maths","chemistry","physics"};
		
		for(String x : subjects) {
			
			System.out.println(x);
		}
	}

}

Example 2: Printing ArrayList using for-each loop

Java for-each Loop code
import java.util.ArrayList;

public class For_each_loop {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		ArrayList<String> subjects = new ArrayList<String>();
		
		subjects.add("computer");
		subjects.add("maths");
		subjects.add("chemistry");
		subjects.add("physics");
		
		for(String x : subjects) {
			
			System.out.println(x);
		}
	}

}

Tutorial MySQL
Tutorial Python
Characteristics of Computer
Wired Networking
TELNET
Application Software
Malicious Software (Malware)
Object-Oriented Programming (OOP)
Java (programming language)– Wikipedia

Comments (No)

Leave a Reply