Java Array Operations Tutorial 🎯

beginner
10 min

Java Array Operations Tutorial 🎯

Welcome to the Java Array Operations tutorial! In this lesson, we'll learn how to create, manage, and perform various operations on arrays in Java. Let's get started!

What is an Array? 📝

An array is a collection of elements of the same data type that are stored in contiguous memory locations. In Java, arrays can be used to store multiple values of a single type.

Creating an Array in Java 💡

To create an array, we first need to declare its data type and size. Here's a simple example of creating an integer array with 5 elements:

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

In this example, int represents the data type, and [5] specifies the size of the array.

Accessing Array Elements 💡

To access an element in an array, we use its index. Array indices start from 0, and the last index is one less than the size of the array. For example:

java
numbers[0] = 10; // setting the first element numbers[4] = 50; // setting the last possible element

Array Length 📝

Every array in Java has a length property that stores the size of the array. To get the length of an array, we can use the length property.

java
int[] numbers = new int[5]; int numElements = numbers.length; // numElements now equals 5

Printing Array Elements 💡

To print all elements in an array, we can use a for loop.

java
int[] numbers = new int[5]; numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }

Array Operations 💡

There are several common operations that we can perform on arrays, such as sorting, searching, and modifying elements. Let's take a look at an example of sorting an array using the built-in Arrays.sort() method.

java
import java.util.Arrays; int[] numbers = new int[] {50, 20, 10, 30, 40}; Arrays.sort(numbers); for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }

Quiz 💡

Quick Quiz
Question 1 of 1

How do we create an integer array with 3 elements in Java?

Conclusion 🎯

In this lesson, we learned how to create arrays in Java, access and modify elements, and perform common operations like sorting. As we continue to explore Java, we'll learn more about advanced array concepts and their practical applications. Happy coding! 🎉