Java Arrays Class 🎯

beginner
12 min

Java Arrays Class 🎯

Welcome to our comprehensive guide on the Java Arrays Class! In this lesson, we'll explore the world of arrays, a fundamental data structure in Java programming. Whether you're a beginner or an intermediate learner, this guide will help you understand arrays from the ground up, with practical examples and real-world applications.

What is an Array? 📝

An array is a data structure that stores a collection of elements of the same type. These elements are stored in contiguous memory locations, allowing us to access them using an index.

Creating an Array in Java 💡

To create an array in Java, we use the new keyword followed by the data type and square brackets []. Here's an example:

java
int[] numbers = new int[5];

In this example, we've created an array called numbers that can store 5 integer values.

Accessing Array Elements 💡

To access an element in an array, we use the index of the element. The index of the first element is 0, and it increases by 1 for each subsequent element.

java
numbers[0] = 10; numbers[1] = 20; numbers[2] = 30;

In this example, we've assigned values to the first three elements of the numbers array.

Array Length 📝

Every array in Java has a length property that indicates the number of elements the array can hold.

java
int length = numbers.length;

In this example, length will be 5, as our numbers array has 5 elements.

Iterating Through an Array 💡

To iterate through an array, we can use a for loop.

java
for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }

In this example, we've printed each element of the numbers array.

Common Array Methods 💡

Java provides several methods to work with arrays. Here are some commonly used ones:

  • public static void fill(int[] a, int val): Fills an array with a specific value.
  • public static void sort(int[] a): Sorts an array in ascending order.
  • public boolean contains(int value): Checks if an array contains a specific value.
  • public int[] clone(): Creates a copy of the array.

Array Examples 💡

Example 1: Filling an Array with Values

java
int[] numbers = new int[5]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i * 10; }

In this example, we've filled the numbers array with values from 0 to 40 (0, 10, 20, 30, 40).

Example 2: Sorting and Checking an Array

java
int[] numbers = {15, 8, 3, 6, 1, 4, 10, 13}; Arrays.sort(numbers); System.out.println(Arrays.binarySearch(numbers, 8)); // Output: 1

In this example, we've sorted the numbers array and found the index of the number 8 using binary search.

Quiz 💡

Quick Quiz
Question 1 of 1

What is the index of the first element in an array?


That's it for our introductory guide to the Java Arrays Class! By understanding arrays, you've taken a significant step towards mastering Java programming. Happy coding! 🚀