Arrays

In Java, arrays are used to store collections of elements of the same data type. Arrays have a fixed size, which means you must specify the size when you declare an array, and you cannot change the size after it's created. Here are some common operations with arrays and examples:

Declaring and Initializing Arrays:

// Declaring an array of integers
int[] numbers;

// Initializing an array with values
int[] primes = {2, 3, 5, 7, 11};

// Initializing an array with a specified size
int[] scores = new int[5];
scores[0] = 95;
scores[1] = 88;
scores[2] = 72;
scores[3] = 90;
scores[4] = 85;

Accessing Array Elements:

// Accessing elements by index
int firstPrime = primes[0]; // firstPrime will be 2

// Modifying elements by index
primes[1] = 13; // Changes the second element to 13

Array Length:

You can find the length of an array using the length property.

Iterating Through an Array:

You can use loops to iterate through the elements of an array.

Multidimensional Arrays:

Java supports multidimensional arrays, including 2D arrays.

Array Copy:

You can copy one array into another using System.arraycopy or by manually iterating through the elements.

Array Sorting:

You can sort arrays using the Arrays.sort method for arrays of primitive types or by implementing the Comparable interface for custom objects.

These are some common operations with arrays in Java. Arrays are a fundamental data structure in Java and are widely used in various programming scenarios.

Last updated

Was this helpful?