Java for Everyone... Arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Declaring a Variable to Refer to an Array
// declares an array of integers
int[] MyFirstArray;
·?????? An array declaration has two components: the array's type and the array's name.
·?????? An array's type is written as type[], where type is the data type of the contained elements
·?????? The brackets are special symbols indicating that this variable holds an array.
·?????? The size of the array is not part of its type (which is why the brackets are empty).
·?????? An array's name can be anything you want as per convention , please refer to this official link.
·?????? Please note that the declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.
Similarly, you can declare arrays of other types:
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
You can also place the brackets after the array's name:
float anArrayOfFloats[];// this form is discouraged
int[] numbers = {11, 10, 19, 87};// Integer array
String[] names = {"Mr Arjun ", "Mr. Mandal", "Mr Jai L"};// String array
double[] prices = {99.89, 49.99, 9.99};//// Double array
2. Declaration and Initialization Separately
You can declare the array first, then initialize it later, please refer below-
int[] numbers;??????? // Declaration
numbers = new int[3];? // Initialization with size 5
// Assigning values
numbers[0] = 11;
numbers[1] = 10;
numbers[2] = 19;
numbers[3] = 87;
// Accessing elements
System.out.println(numbers[0]); // Output: 11
A Basic Program
public static void main(String[] args) {
// 1D array
int[] numbers = { 11, 10, 19, 87 };
System.out.println("Print My first 1D array");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + "" + numbers[i]);
}
// 2D array
int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
System.out.println("\n Print My first 2D array:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
output
Print My first 1D array
Element at index 011
Element at index 110
Element at index 219
Element at index 387
Print My first 2D array:
1 2 3
4 5 6
7 8 9
3. Using the new Keyword with Explicit Values
This is a hybrid approach where you declare and initialize using the new keyword and provide values.
int[] numbers = new int[] {10, 20, 30, 40, 50};
int[][] matrix = new int[3][3]; // 3x3 matrix
// Assigning values
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
4. Default Initialization
If you only declare and initialize an array without assigning values, it gets initialized with default values based on its type.
int[] numbers = new int[5]; // Default values: [0, 0, 0, 0, 0]
boolean[] flags = new boolean[3]; // Default values: [false, false, false]
String[] names = new String[4]; // Default values: [null, null, null, null]
5. Using a Loop for Initialization
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
??? numbers[i] = i * 11; // Assign multiples of 11
}
// Output the values
for (int number : numbers) {
??? System.out.println(number);
}
6. Array Inside a Method
In Java, arrays can be passed as method arguments to allow the method to work with multiple values. Arrays are passed by reference, meaning the method receives a reference to the actual array, not a copy of it. This allows the method to modify the contents of the original array if needed
You define a method that takes an array as an argument like this:
returnType methodName(dataType[] arrayName) { // method body }
public static void main(String[] args) {
int[] numbers = {11,10,19,87};
// Call the method
modifyArray(numbers);
// Print the modified array
for (int num : numbers) {
System.out.println(num);
}
}
// Method to modify array elements
public static void modifyArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 41; // Multiply each element by *41
}
}
Loops in Array
In Java, the iteration loop and for loop generally refer to the different ways to iterate over elements or execute a block of code multiple times. However, they can be used interchangeably depending on the context. Let’s break down the differences and usage scenarios for each:
The for loop is a general-purpose loop that gives you full control over initialization, condition checking, and iteration.
Syntax-
for (initialization; condition; increment/decrement) {
??// Code to execute
}
Initialization: Defines a variable (usually a counter) and sets it to a starting value.
Condition: Specifies the condition for the loop to run. The loop continues as long as the condition is true.
Increment/Decrement: Modifies the counter variable after each iteration.
// Print numbers 1 to 9
for (int i = 1; i <= 9; i++) {
??? System.out.println(i);
}
Explanations- Starts with i = 1, continues while i <= 9, and increments i after each iteration until i becomes 10.
2. Enhanced For Loop (aka For-Each Loop)
Syntax
for (datatype element : array_or_collection) {
??? // Code to execute using 'element'
}
datatype: The type of each element in the array/collection (e.g., int, String, etc.).
element: A variable that holds the current element of the array or collection during each iteration.
array_or_collection: The array or collection being iterated.
Examples-
Ex1-
// Iterate through an array using enhanced for loop
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
Ex2-
String[] colors = {"Red", "Green", "Blue"};
for (String color : colors) {
System.out.println(color); // Access each element directly
}
Use the Traditional for Loop:
·??? When you need to access the index of elements.
·????When iterating with a non-array or collection, or when the loop's starting index or termination condition is non-trivial.
·???When working with multi-dimensional arrays or complex iteration patterns.
Use the Enhanced for Loop:
·????When iterating over collections or arrays and you don’t need to manipulate the index.
·??? For simpler, more readable code where you just need to process each element.
Key features of arrays in Java
Also note-
Size Specification-You cannot resize an array after it is initialized. For dynamic resizing, use collections like ArrayList.
Default Values: Primitive types (int, float, etc.) are initialized to 0.
Boolean arrays are initialized to false.
Reference types (e.g., String, Integer) are initialized to null.
Out-of-Bounds Error:Accessing an index outside the array bounds will throw an ArrayIndexOutOfBoundsException.
/*
This is article is based on JDK 8, any changes on features, enhancement or deprecated options can be referred to official release notes-
*/