Java Basic Tutorial
Java Advance Tutorial
In Java, arrays themselves are not objects with built-in methods, but you can use methods from utility classes like java.util.Arrays
to manipulate arrays. Here's a list of basic operations and common methods used with arrays in Java:
Method |
Description |
Example |
---|---|---|
Returns the number of elements in the array |
int[] arr = {10, 20, 30, 40, 50}; System.out.println(arr.length); // Output: 5 |
|
Converts an array to a string. |
import java.util.Arrays; int[] arr = {10, 20, 30}; System.out.println(Arrays.toString(arr)); // Output: [10, 20, 30] |
|
Searches for a key in a sorted array. |
import java.util.Arrays; int[] arr = {10, 20, 30, 40}; int index = Arrays.binarySearch(arr, 30); System.out.println(index); // Output: 2 |
|
Compares two arrays for equality. |
import java.util.Arrays; int[] arr1 = {10, 20, 30}; int[] arr2 = {10, 20, 30}; System.out.println(Arrays.equals(arr1, arr2)); // Output: true |
|
Compares two multi-dimensional arrays for equality. |
import java.util.Arrays; int[][] arr1 = {{1, 2}, {3, 4}}; int[][] arr2 = {{1, 2}, {3, 4}}; System.out.println(Arrays.deepEquals(arr1, arr2)); // Output: true |
|
Fills an array with a specific value. |
import java.util.Arrays; int[] arr = new int[5]; Arrays.fill(arr, 7); System.out.println(Arrays.toString(arr)); // Output: [7, 7, 7, 7, 7] |
|
Sorts an array in ascending order. |
import java.util.Arrays; int[] arr = {30, 10, 20, 50}; Arrays.sort(arr); System.out.println(Arrays.toString(arr)); // Output: [10, 20, 30, 50] |
|
Copies an array to a new array. |
import java.util.Arrays; int[] original = {1, 2, 3}; int[] copy = Arrays.copyOf(original, original.length); System.out.println(Arrays.toString(copy)); // Output: [1, 2, 3] |
The length
property is used to find the size of an array.
Try it yourself
Converts an array to a string.
Try it yourself
Searches for a key in a sorted array.
Try it yourself
Arrays.equals()
→ Compares two arrays for equality.Arrays.deepEquals()
→ Compares two multi-dimensional arrays for equality.Try it yourself
Try it yourself
Fills an array with a specific value.
Try it yourself
Sorts an array in ascending order.
Try it yourself
Copies an array to a new array.
Try it yourself