This code defines a class ArrayMethodsExample
that demonstrates various methods provided by the java.util.Arrays
class.
The main method first initializes several arrays and demonstrates some of the methods of the Arrays
class.
Arrays.fill()
fills the specified range of elements in an array with a specified value. In this case, the range of elements from 0 to 2 in the array myFirstArray
is filled with the value 5.Arrays.sort()
sorts an array in ascending order. In this case, the myFirstArray
is sorted.Arrays.asList().contains()
checks if the specified element exists in an array. In this case, it checks if the element “a” exists in the myFourthArray
.Arrays.toString()
returns a string representation of an array. In this case, it returns the string representation of the myThirdArray
.Arrays.copyOfRange()
creates a new array that is a copy of a specified range of elements from an existing array. In this case, it creates a copy of the elements from the myThirdArray
starting from index 0 to 10.Arrays.equals()
compares two arrays and returns true if they contain the same elements in the same order. In this case, it compares the mySecondArray
and myThirdArray
and returns true if they are the same.import java.util.Arrays;
public class ArrayMethodsExample {
public static void main(String[] args) {
int[] myFirstArray = { 1, 2, 3, 4 };
int[] mySecondArray = { 5, 6, 7, 8 };
int[] myThirdArray = { 5, 6, 7, 8 };
String[] myFourthArray = { "a", "b", "c", "d" };
boolean isSame = Arrays.equals(mySecondArray, myThirdArray);
boolean inArray = Arrays.asList(myFourthArray).contains("a");
System.out.print("Fill Array: ");
Arrays.fill(myFirstArray, 0, 2, 5);
for (int i = 0; i < myFirstArray.length; i++) {
System.out.print(myFirstArray[i]);
}
System.out.print("\nSorted Array: ");
Arrays.sort(myFirstArray);
for (int i = 0; i < myFirstArray.length; i++) {
System.out.print(myFirstArray[i]);
}
System.out.println("\ncontains: " + inArray);
System.out.println("array as string: " + Arrays.toString(myThirdArray));
System.out.println("length before copyOfRange: " + myThirdArray.length);
myThirdArray = Arrays.copyOfRange(myThirdArray, 0, 10);
System.out.println("length after copyOfRange: " + myThirdArray.length);
System.out.println("equals: " + isSame);
}
}
Fill Array: 5534
Sorted Array: 3455
contains: true
array as string: [5, 6, 7, 8]
length before copyOfRange: 4
length after copyOfRange: 10
equals: true