Arrays are a fundamental data structure in Java, used to store multiple values of the same type in a single variable. Understanding how to perform common operations on arrays is essential for efficient programming.
Creating and Initializing Arrays
Syntax
dataType[] arrayName =newdataType[arraySize];Offerto da
dataType: The type of elements the array will hold (e.g., int, String).
arrayName: The name of the array.
arraySize: The number of elements the array can hold.
Example
int[] numbers =newint[5];// Array of integers with size 5
String[] names ={"Alice","Bob","Charlie"};// Array initialized with valuesOfferto da
Accessing Array Elements
Array elements are accessed using their index, starting from 0.
Example
int[] numbers ={10,20,30};
System.out.println(numbers[0]);// Outputs 10Offerto da
Modifying Array Elements
You can modify elements by assigning a new value to a specific index.
Example
int[] numbers ={10,20,30};
numbers[1]=50;// Changes the second element to 50Offerto da
Iterating Over Arrays
Using a for Loop
int[] numbers ={10,20,30};for(int i =0; i < numbers.length; i++){
System.out.println(numbers[i]);}Offerto da
Using a for-each Loop
int[] numbers ={10,20,30};for(int number : numbers){
System.out.println(number);}Offerto da
Finding the Length of an Array
The length of an array is accessed using the length property.
Example
int[] numbers ={10,20,30};
System.out.println("Array length: "+ numbers.length);// Outputs 3Offerto da
Copying Arrays
Using System.arraycopy()
int[] source ={1,2,3};
int[] destination =newint[3];
System.arraycopy(source,0, destination,0, source.length);Offerto da
Arrays are a fundamental data structure in Java, used to store multiple values of the same type in a single variable. Understanding how to perform common operations on arrays is essential for efficient programming.
Creating and Initializing Arrays
Syntax
int,String).Example
Accessing Array Elements
Array elements are accessed using their index, starting from 0.
Example
Modifying Array Elements
You can modify elements by assigning a new value to a specific index.
Example
Iterating Over Arrays
Using a
forLoopUsing a
for-eachLoopFinding the Length of an Array
The length of an array is accessed using the
lengthproperty.Example
Copying Arrays
Using
System.arraycopy()Using
Arrays.copyOf()Sorting Arrays
Using
Arrays.sort()Searching Arrays
Using
Arrays.binarySearch()Note: The array must be sorted before using
binarySearch().Tips and Best Practices
ArrayIndexOutOfBoundsException.Collections.unmodifiableList()if you need an immutable array-like structure.System.arraycopy()for better performance when copying large arrays.for-eachloop for readability when you do not need the index.Arraysclass for operations like sorting and searching to simplify code.