|
| 1 | +# Arrays |
| 2 | + |
| 3 | +## **What is an Array?** |
| 4 | + |
| 5 | +An array is the simplest data structure where a collection of similar data elements takes place and each data element can be accessed directly by only using its index number. |
| 6 | + |
| 7 | +## One-Dimensional Arrays |
| 8 | + |
| 9 | +### **1. Declaration and then Initialization** |
| 10 | + |
| 11 | +First, you declare an array by specifying the data type of its elements, followed by square brackets `[ ]` (which indicate it's an array), and then the array's name. After declaring, you can initialize it by allocating memory with the `new` keyword and specifying the size of the array. |
| 12 | + |
| 13 | +```java |
| 14 | +// Declaration |
| 15 | +int[] myArray; |
| 16 | +int myArray1[]; |
| 17 | +// Initialization |
| 18 | +myArray = new int[5]; // Allocate memory for 5 integers |
| 19 | +``` |
| 20 | + |
| 21 | +### **2. Declaration with Initialization** |
| 22 | + |
| 23 | +You can declare an array and immediately initialize it with values. In this case, the size of the array is inferred from the number of values provided. |
| 24 | + |
| 25 | +```java |
| 26 | +// Declare and initialize an array with 5 elements |
| 27 | +int[] myArray1 = new int[]{1, 2, 3, 4, 5}; |
| 28 | + |
| 29 | +int[] myArray = {1, 2, 3, 4, 5}; |
| 30 | +``` |
| 31 | +### **3. Using the `new` Keyword** |
| 32 | + |
| 33 | +For more dynamic scenarios, where you might not know the values upfront but know the size of the array, you can use the **`new`** keyword to allocate memory for the array. You can then assign values to each element using their indices. |
| 34 | + |
| 35 | +```java |
| 36 | +// Declare and allocate memory for an array of 5 elements |
| 37 | +int[] myArray = new int[5]; |
| 38 | + |
| 39 | +// Initialize elements |
| 40 | +myArray[0] = 10; |
| 41 | +myArray[1] = 20; |
| 42 | +myArray[2] = 30; |
| 43 | +myArray[3] = 40; |
| 44 | +myArray[4] = 50; |
| 45 | +``` |
| 46 | + |
| 47 | +## **How to print elements of an Array in Java?** |
| 48 | + |
| 49 | +### **1. Using a For Loop** |
| 50 | + |
| 51 | +You can iterate over the array using a traditional `for` loop and print each element individually. |
| 52 | + |
| 53 | +```java |
| 54 | +public class Main { |
| 55 | + public static void main(String[] args) { |
| 56 | + int[] numbers = {10, 20, 30, 40, 50}; |
| 57 | + |
| 58 | + // Using a for loop to print elements |
| 59 | + System.out.println("Using for loop:"); |
| 60 | + for (int i = 0; i < numbers.length; i++) { |
| 61 | + System.out.println("Element at index " + i + ": " + numbers[i]); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | + |
0 commit comments