Arrays.toString() method is a tool in Java that helps us turn arrays into strings. A string is just a bunch of letters, numbers, or symbols that are written out. By using Arrays.toString(), we can take an array and turn it into a string that we can read or print out.
Here's an example of how to use Arrays.toString() in Java:
javaimport java.util.Arrays;
public class Example {
public static void main(String[] args) {
int[] arr = {10, 20, 30};
System.out.println(Arrays.toString(arr)); // Output: [10, 20, 30]
}
}
In this example, we have an array of numbers called "arr". We want to turn this array into a string that we can read, so we use Arrays.toString() to do it. We call the method by typing "Arrays.toString(arr)" and it returns a string that looks like this: "[10, 20, 30]".
Note that we can also use Arrays.toString() with objects. Here's an example of how to use a custom object with Arrays.toString():
javaimport java.util.Arrays;
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Name: " + name + ", Age: " + age;
}
}
public class Example {
public static void main(String[] args) {
Person[] people = {
new Person("Bob", 25),
new Person("Alice", 30),
new Person("Charlie", 35)
};
System.out.println(Arrays.toString(people)); // Output: [Name: Bob, Age: 25, Name: Alice, Age: 30, Name: Charlie, Age: 35]
}
}
In this example, we have an array of "Person" objects. We use Arrays.toString() to turn this array into a string that we can read. The "Person" class has its own "toString()" method that returns a string with the person's name and age. When we use Arrays.toString() with the "people" array, it returns a string that looks like this: "[Name: Bob, Age: 25, Name: Alice, Age: 30, Name: Charlie, Age: 35]".
Overall, Arrays.toString() is a helpful method in Java that allows us to turn arrays into readable strings. It's a useful tool to have in your programming toolbox!