Sunday, April 27, 2025

Java Tutorial - Arrays and ForEach Loop

An array is a data structure that stores a fixed-size, ordered collection of elements of the same type. The elements of an array can be accessed using an index, which is an integer value that represents the position of an element in the array.

In Java, arrays are declared using square brackets []. The elements of the array can be of any primitive data type or any object type.

This Java program defines a class called Main with a main method that contains three different examples of using the "enhanced for loop" (also known as the "for-each loop") to iterate over the elements of an array.

public class Main {

	public static void main(String[] args) {
		
		/*String[] progLang = {"Python", "C++", "Perl", "Lisp", "Java"};
		
		for (String x: progLang) {
			System.out.println(x);
		}*/
		
		/*int[] numbers = {1, 3, 5, 55, 76, 1000};
		
		for (int x: numbers) {
			System.out.println(x);
		}*/
		
		char[] charArr = {'A', 'B', 'Z', 'Z', 'Z'};
		
		for (char x: charArr) {
			System.out.println(x);
		}		
		
	}	
}

An array of characters named charArr is defined and initialized with the values 'A', 'B', 'Z', 'Z', and 'Z'. Then, a for-each loop is used to iterate over the elements of the charArr array.

In each iteration of the loop, the next element of the array is assigned to the loop variable x, which has been declared as a char type. Then, the println() method of the System.out object is called with the loop variable x as an argument, causing the current element of the array to be printed to the console.

Therefore, when this code runs, it will print the characters 'A', 'B', 'Z', 'Z', and 'Z' to the console, each on a separate line.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...