
- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use for and foreach loops to display elements of an array using Java
Problem Description
How to use for and foreach loops to display elements of an array.
Solution
This example displays an integer array using for loop & foreach loops.
public class Main { public static void main(String[] args) { int[] intary = { 1,2,3,4}; forDisplay(intary); foreachDisplay(intary); } public static void forDisplay(int[] a) { System.out.println("Display an array using for loop"); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(); } public static void foreachDisplay(int[] data) { System.out.println("Display an array using for each loop"); for (int a : data) { System.out.print(a+ " "); } } }
Result
The above code sample will produce the following result.
Display an array using for loop 1 2 3 4 Display an array using for each loop 1 2 3 4
The following is an another sample example of Foreach
import java.util.*; public class HelloWorld { public static void main(String args[]) { ArrayList<String> list = new ArrayList<String>(); list.add("Tutorials"); list.add("Point"); list.add("India PVT Limited"); for(String s:list) { System.out.println(s); } } }
Result
The above code sample will produce the following result.
Tutorials Point India PVT Limited
java_methods.htm
Advertisements