1. Java Arrays
Java provides a data structure called an array, which stores a fixed-size sequential collection of elements of the same type. This is also described as homogeneous data.
An array is useful for storing a collection of values. Instead of declaring individual variables such as number0, number1, ... number99, one array variable can represent them through indexed elements such as numbers[0], numbers[1], ... numbers[99].
2. Declaring Array Variables
To use an array in a program, declare a variable that references the array and specify the type of array the variable can reference.
Syntax
dataType[] arrayRefVar; // preferred way dataType arrayRefVar[]; // works but not preferred
Example
double[] myList; // preferred way double myList[]; // works but not preferred
dataType[] arrayRefVar as the preferred declaration style.
3. Creating Arrays
You can create an array by using the new operator.
Syntax
arrayRefVar = new dataType[arraySize];
The statement performs two operations:
- Creates an array using
new dataType[arraySize]. - Assigns the reference of the newly created array to
arrayRefVar.
Array Indexing
Array indexes start at 0. For an array of size n, the valid indexes range from 0 through n - 1.
4. Processing Arrays
When processing array elements, we often use either a for loop or a foreach loop, because all elements have the same type and the array size is known.
Using a for Loop
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max)
max = myList[i];
}
System.out.println("Max is " + max);
}
}
This example demonstrates three common array operations: printing every element, calculating the total, and finding the largest element.
5. The foreach Loop
The enhanced for loop provides a simple way to visit every element without explicitly managing an index.
Example
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element : myList) {
System.out.println(element);
}
}
}
for (Type element : array) assigns each array element to the loop variable one at a time.
6. Passing Arrays to Methods
Arrays can be passed to methods just like other reference-type values.
Example
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
The method receives an int[] parameter and can access its elements using the index.
7. Returning an Array from a Method
A method may also return an array. The source provides an example that returns the reverse of another array.
Example
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length;
i++, j--) {
result[j] = list[i];
}
return result;
}
int[], meaning it returns a reference to an integer array.
8. Types of Arrays in Java
The source identifies two broad types of arrays:
1. Single-Dimensional Array
An array with only one subscript or one dimension. It is a list of variables of the same data type.
2. Multi-Dimensional Array
An array in which elements can themselves be organized into additional dimensions, such as 2D, 3D and beyond.
Single-Dimensional Array
int[] a = {10, 20, 30, 40, 50};
Conceptually, a one-dimensional array looks like:
a[0] a[1] a[2] ... a[n-1]
Multi-Dimensional Array
Sometimes a program needs an array within an array. A common example is a two-dimensional matrix.
9. Multi-Dimensional Arrays
The source illustrates a two-dimensional array using rows and columns.
Declaration and Initialization
int marks[][] = {
{77,85,68,99,87},
{98,56,79,90,92},
{78,88,56,70,99}
};
OR
int marks[][] = new int[3][5];
Two-Dimensional Matrix Example
public class Demo {
public static void main (String[] args) {
// declaring and initializing arrays
int arr1[][] = {{1,2,3},{4,5,6},{7,8,9}};
int arr2[][] = {{2,2,2},{2,2,2},{2,2,2}};
// Printing Array1 in matrix format
System.out.println("Array1 -");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
System.out.print(arr1[i][j] + " ");
}
System.out.println();
}
// Printing Array2 in matrix format
System.out.println("Array2 -");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
System.out.print(arr2[i][j] + " ");
}
System.out.println();
}
int arr3[][] = new int[3][3];
}
}
10. Matrix Multiplication
The source uses matrix multiplication as a well-known example of a 2D array. Two 3×3 arrays are multiplied and the result is stored in a third 3×3 array.
Core Logic
// Multiplying arr1 and arr2, storing results in arr3
System.out.println("Multiplication of Array1 and Array2 - ");
for(int i=0;i<arr1.length;i++) {
for(int j=0;j<arr2.length;j++) {
arr3[i][j] = 0;
for(int k=0;k<arr3.length;k++) {
arr3[i][j] += arr1[i][k] * arr2[k][j];
}
System.out.print(arr3[i][j] + " ");
}
System.out.println();
}
Output
Array1 - 1 2 3 4 5 6 7 8 9 Array2 - 2 2 2 2 2 2 2 2 2 Multiplication of Array1 and Array2 - 12 12 12 30 30 30 48 48 48
11. Arrays of Objects
An array of objects is an array that stores references to objects. The array does not contain the complete object instances directly; its elements are object reference variables.
Syntax
Student studentObj[] = new Student[3];
This creates an array of length 3 containing three Student references. Each reference can then be initialized using new.
Example
class Student {
Student(int id, String name) {
System.out.println("Student ID is " + id + " and name is " + name);
}
}
public class Test {
public static void main (String[] args) {
// declaring an array of Object
Student obj[] = new Student[3];
obj[0] = new Student(1,"Bharat");
obj[1] = new Student(5,"Vivaan");
obj[2] = new Student(6,"Smith");
}
}
Output
Student ID is 1 and name is Bharat Student ID is 5 and name is Vivaan Student ID is 6 and name is Smith
The source explains that the array first creates three reference variables, obj[0], obj[1] and obj[2]. Each reference is then initialized with a separate new Student(...) object.
12. Advantages and Disadvantages of Arrays in Java
Advantages
- Array elements can be accessed randomly using their index.
- Many values can be stored at a time.
- It is easier to create and work with multi-dimensional arrays.
Disadvantages
- Java arrays do not have built-in
removeoraddmethods. - The size must be specified, which can result in memory wastage when the required size changes.
- The source recommends
ArrayListwhen dynamic sizing is required. - Arrays in Java are strongly typed.
13. Conclusion & Quick Revision
- An array in Java is a non-primitive data type used to store multiple values of the same data type.
- Array elements are accessed using indexes from 0 to length - 1.
- A
forloop and enhancedfor-eachloop can be used to traverse array elements. - Java supports single-dimensional and multi-dimensional arrays, including 2D, 3D and nD forms.
- Arrays can contain primitive values as well as references to objects.
- Arrays can be passed to methods and returned from methods.
- An array without a named variable is commonly called an anonymous array for immediate use.
- The source also mentions using
clone()for duplicating arrays.
Frequently Asked Questions
| Question | Answer |
|---|---|
| What is an array? | A homogeneous non-primitive data type used to store multiple same-type values in one variable. |
| Are arrays reference types in Java? | Yes. An array is a reference type and is treated as a reference to an array object. |
| Are arrays primitive data types? | No. Arrays are non-primitive/reference types, although they can hold primitive values. |
| Can you increase the size of an array? | No. Once an array is created, its length cannot be changed at runtime. A new array or a dynamic collection such as ArrayList is needed. |