Java Arrays - Methods, Examples & Real-Time Use Cases
Java Arrays Methods with Examples
1. [Link]()
Converts the array to a string format.
import [Link];
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
[Link]([Link](arr)); // [1, 2, 3, 4]
}
}
2. [Link]()
Sorts the array in ascending order.
import [Link];
public class Main {
public static void main(String[] args) {
int[] arr = {5, 1, 4, 2};
[Link](arr);
[Link]([Link](arr)); // [1, 2, 4, 5]
}
}
3. [Link]()
Copies the specified array, truncating or padding with default values.
import [Link];
public class Main {
public static void main(String[] args) {
int[] original = {1, 2, 3};
int[] copy = [Link](original, 5);
[Link]([Link](copy)); // [1, 2, 3, 0, 0]
}
}
4. [Link]()
Checks if two arrays are equal.
import [Link];
public class Main {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
Java Arrays - Methods, Examples & Real-Time Use Cases
[Link]([Link](a, b)); // true
}
}
5. [Link]()
Fills the array with a specific value.
import [Link];
public class Main {
public static void main(String[] args) {
int[] arr = new int[5];
[Link](arr, 7);
[Link]([Link](arr)); // [7, 7, 7, 7, 7]
}
}
Real-Time Use Cases of Arrays
Use Case 1: Finding the missing number in a range
import [Link].*;
public class MissingNumber {
public static void main(String[] args) {
int[] nums = {1, 2, 4, 6, 3, 7, 8};
int n = 8;
int sum = (n * (n + 1)) / 2;
for (int num : nums) {
sum -= num;
}
[Link]("Missing number: " + sum); // Output: 5
}
}
Use Case 2: Remove duplicates from sorted array
import [Link];
public class RemoveDuplicates {
public static int removeDuplicates(int[] nums) {
int i = 0;
for (int j = 1; j < [Link]; j++) {
if (nums[i] != nums[j]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
Java Arrays - Methods, Examples & Real-Time Use Cases
public static void main(String[] args) {
int[] arr = {1, 1, 2, 2, 3};
int len = removeDuplicates(arr);
for (int i = 0; i < len; i++) {
[Link](arr[i] + " ");
}
}
}
Use Case 3: Two Sum Problem
import [Link].*;
public class TwoSum {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < [Link]; i++) {
int complement = target - nums[i];
if ([Link](complement)) {
[Link]("Indices: " + [Link](complement) + ", " + i);
break;
}
[Link](nums[i], i);
}
}
}