Back to Java
2026-04-287 min read

Swift Arrays (Java)

Learn Swift Arrays (Java) step by step with clear examples and exercises.

Why This Matters

Learning how to use and manipulate arrays in Java is crucial for any programmer as they are fundamental data structures used in programming to store multiple values of the same type. Understanding arrays is essential for solving real-world problems, debugging complex code, and acing coding interviews. Arrays allow efficient storage and retrieval of large amounts of data, making them an indispensable tool in a programmer's arsenal.

Prerequisites

Before diving into arrays, you should have a good understanding of the following:

  1. Basic Java syntax (variables, operators, control structures)
  2. Classes and Objects
  3. Methods
  4. Exception handling to be aware of common errors such as ArrayIndexOutOfBoundsException and NullPointerException.
  5. Understanding of the concept of data types and their importance in arrays.
  6. Familiarity with Java libraries like Arrays, which provide useful methods for working with arrays.
  7. Understanding of loops (for, while, do-while) and conditional statements (if, else if, else).
  8. Knowledge of static and instance variables.
  9. Understanding of the concept of objects and their properties (fields).
  10. Familiarity with basic file I/O operations in Java.

Core Concept

Creating an Array

In Java, arrays are objects that hold elements of the same data type. To create an array, you first need to declare a variable with the desired data type and size. Then, you allocate memory for the array using the new keyword.

int[] myArray = new int[5]; // Declare an array of integers with 5 elements
String[] myStrings = new String[3]; // Declare an array of strings with 3 elements
boolean[] myBooleans = new boolean[10]; // Declare an array of booleans with 10 elements

Accessing Array Elements

You can access individual elements using their index, which starts at 0 for the first element.

myArray[0] = 10; // Assign a value to the first element
System.out.println(myArray[0]); // Output: 10
myStrings[0] = "Apple"; // Assign a value to the first string element
System.out.println(myStrings[0]); // Output: Apple

Manipulating Array Elements

You can change the values of array elements and even add or remove elements using various methods like length, for loops, and built-in Java utilities such as Arrays.

myArray[1] = 20; // Assign a value to the second element
System.out.println(myArray[1]); // Output: 20

// Using for loop to print all elements
for (int i = 0; i < myArray.length; i++) {
System.out.println("Element " + i + ": " + myArray[i]);
}

Initializing Arrays

When creating an array, it is important to initialize the elements with appropriate values or default values if necessary. This can be done either by using an initializer list or by assigning values within a loop.

// Using initializer list
int[] myArray = {1, 2, 3, 4, 5}; // Declare and initialize an array with 5 elements

// Initializing within a loop
int[] myArray = new int[5];
for (int i = 0; i < myArray.length; i++) {
myArray[i] = i * 2 + 1; // Initialize each element with a specific value
}

Multi-dimensional Arrays

Java also supports multi-dimensional arrays, which can be created by declaring multiple sets of square brackets.

int[][] my2DArray = new int[3][4]; // Declare a 2D array with 3 rows and 4 columns
my2DArray[0][0] = 1; // Access the first element in the first row
System.out.println(my2DArray[0][0]); // Output: 1

Array Properties and Methods

Arrays in Java have several useful properties and methods, such as length, clone(), and equals().

  • The length property returns the number of elements in the array.
  • The clone() method creates a copy of the array.
  • The equals() method checks if two arrays are equal.
int[] myArray = {1, 2, 3};
System.out.println("Array length: " + myArray.length); // Output: 3

int[] copyOfMyArray = myArray.clone(); // Create a copy of the array
System.out.println("Copy of Array length: " + copyOfMyArray.length); // Output: 3

int[] anotherArray = {1, 2, 3};
boolean isEqual = Arrays.equals(myArray, anotherArray); // Check if arrays are equal
System.out.println("Arrays are equal: " + isEqual); // Output: true

Worked Example

Let's create an array of integers to store the marks of five students in a test, find the average mark, and sort the array using the Arrays class.

public class ArrayExample {
public static void main(String[] args) {
int[] studentMarks = new int[]{95, 86, 78, 100, 82}; // Declare and initialize an array with student marks

// Find the average mark
double sum = Arrays.stream(studentMarks).sum();
double average = sum / studentMarks.length;
System.out.println("Average Mark: " + average);

// Sort the array using Arrays.sort() method
Arrays.sort(studentMarks);
System.out.println("Sorted Array: " + Arrays.toString(studentMarks));
}
}

Output:

Average Mark: 88.4
Sorted Array: [78, 82, 86, 95, 100]

Common Mistakes

Forgetting Array Index Bounds

Ensure that the index you use is within the bounds of the array to avoid ArrayIndexOutOfBoundsException.

// Wrong: myArray[-1] = 10; // This will throw an exception
myArray[4] = 50; // Correct, if the array has 5 elements

Not Initializing Arrays

Always initialize arrays before using them to avoid NullPointerException.

// Wrong: int[] myArray; myArray[0] = 10; // This will throw an exception
int[] myArray = new int[5]; // Correct

Forgetting to Increment the Loop Counter

Ensure that you increment the loop counter after each iteration.

// Wrong: for (int i = 0; i <= myArray.length; i++) { ... } // This will throw an exception
for (int i = 0; i < myArray.length; i++) { ... } // Correct

Using the Wrong Data Type

Ensure that you use the correct data type for your array elements.

// Wrong: String[] myArray = new int[5]; // This will throw a compilation error
String[] myArray = new String[5]; // Correct

Not Clearing Array Elements Before Reuse

When reusing an array, it's important to clear its elements before assigning new values to avoid unintended data retention.

// Wrong: int[] myArray = {1, 2, 3}; myArray[0] = "Hello"; // This will throw a compilation error
int[] myArray = {1, 2, 3}; // Declare an array of integers
Arrays.fill(myArray, -1); // Clear the elements
myArray[0] = "Hello"; // Assign a new value to the first element

Practice Questions

  1. Write a program to create an array of strings and store the names of five countries. Then, print each country's name using a for loop.
  2. Create an array of integers that stores the marks of 10 students in a test. Calculate the average mark using the Arrays class and find the highest mark.
  3. Write a program to create an array of integers and find the second-highest number in the array.
  4. Create a multi-dimensional array to store the grades of 5 students in 3 subjects. Calculate the average grade for each student and print them out.
  5. Write a program that takes user input for the size of an array, creates the array, and then allows the user to enter elements into the array using a loop. Finally, sort the array and print its contents.
  6. Create a program that reads a list of words from a file and stores them in an array. Then, find the longest word in the array.
  7. Write a program that creates an array of integers representing a temperature sequence. Find the minimum and maximum temperatures in the sequence using the Arrays class.
  8. Create a program that reads a list of numbers from standard input and stores them in an array. Calculate the sum of all even numbers in the array.
  9. Write a program that creates an array of strings representing names of employees in a company. Find the employee with the longest name using the Arrays class.
  10. Create a program that reads a list of words from standard input and stores them in a set (using HashSet). Find the word that appears most frequently in the set.

FAQ

How do I find the sum of all elements in an array?

You can use the built-in Java utility Arrays to calculate the sum of all elements in an array.

int[] myArray = {1, 2, 3, 4, 5}; // Declare and initialize an array
int sum = Arrays.stream(myArray).sum(); // Calculate the sum using streams
System.out.println("The sum of all elements is: " + sum);

How do I sort an array in Java?

You can use the Arrays.sort() method to sort an array in ascending order.

int[] myArray = {5, 3, 1, 4, 2}; // Declare and initialize an array
Arrays.sort(myArray); // Sort the array
System.out.println("Sorted array: " + Arrays.toString(myArray));

How do I search for a specific element in an array?

You can use the Arrays.binarySearch() method to find the index of a specific element in a sorted array. If the element is not found, it will return a negative value.

int[] myArray = {1, 2, 3, 4, 5}; // Declare and initialize a sorted array
int target = 3; // Search for this element
int index = Arrays.binarySearch(myArray, target);
System.out.println("Element found at index: " + index);

How do I copy an array in Java?

You can use the clone() method to create a copy of an array.

int[] myArray = {1, 2, 3}; // Declare and initialize an array
int[] copyOfMyArray = myArray.clone(); // Create a copy of the array

How do I reverse an array in Java?

You can use the Arrays.copyOf() method along with the reverse() method from the Collections class to reverse an array.

int[] myArray = {1, 2, 3}; // Declare and initialize an array
List<Integer> reversedList = new ArrayList<>(Arrays.asList(myArray)); // Convert the array to a list
Collections.reverse(reversedList); // Reverse the list
int[] reversedArray = reversedList.stream().mapToInt(i -> i).toArray(); // Convert the reversed list back to an array
Swift Arrays (Java) | Java | XQA Learn