[Go to site: main page, start]

0% found this document useful (0 votes)
5 views4 pages

Java Array Inbuilt Methods Explained

Uploaded by

Mohan Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Java Array Inbuilt Methods Explained

Uploaded by

Mohan Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Array Inbuilt Methods

1. Printing an Array (toString())


Used to print the array in a readable format.

Example:
```java
import [Link];
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
[Link]([Link](arr));
}
}
```
Output:
[1, 2, 3, 4, 5]

2. Sorting an Array (sort())


Used to sort an array in ascending order.

Example:
```java
import [Link];
public class Main {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 3};
[Link](arr);
[Link]([Link](arr));
}
}
```
Output:
[1, 2, 3, 5, 8]

3. Filling an Array (fill())


Used to fill an array with a specific value.
Example:
```java
import [Link];
public class Main {
public static void main(String[] args) {
int[] arr = new int[5];
[Link](arr, 7);
[Link]([Link](arr));
}
}
```
Output:
[7, 7, 7, 7, 7]

4. Copying an Array (copyOf, copyOfRange())


Used to copy an array or a portion of it.

Example:
```java
import [Link];
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int[] copy = [Link](arr, [Link]);
[Link]([Link](copy));
}
}
```
Output:
[1, 2, 3, 4, 5]

5. Comparing Arrays (equals())


Checks if two arrays are equal.

Example:
```java
import [Link];
public class Main {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
[Link]([Link](arr1, arr2));
}
}
```
Output:
true

6. Searching in an Array (binarySearch())


Used to search for an element in a sorted array.

Example:
```java
import [Link];
public class Main {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9};
int index = [Link](arr, 5);
[Link]("Index of 5: " + index);
}
}
```
Output:
Index of 5: 2

7. Converting an Array to a List (asList())


Converts an array into a List.

Example:
```java
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie"};
List<String> list = [Link](names);
[Link](list);
}
}
```
Output:
[Alice, Bob, Charlie]

8. Multi-dimensional Arrays (deepToString(), deepEquals())


Used to print and compare multi-dimensional arrays.

Example:
```java
import [Link];
public class Main {
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
[Link]([Link](matrix));
}
}
```
Output:
[[1, 2, 3], [4, 5, 6]]

You might also like