Arrays.toString
- Java course
- Beginner
- Lesson 60/116
- 4 min
Learn to print arrays with Arrays.toString.
Printing arrays: Arrays.toString
If you print an array directly with System.out.println, Java shows a meaningless address like [I@1b6d3586. Instead, Arrays.toString turns the array into readable text.
int[] nums = {3, 1, 2};
System.out.println(Arrays.toString(nums));
// [3, 1, 2]The method returns a String, so you can use it inside println comfortably. The output is wrapped in square brackets and elements are separated by commas.
Formatting the array text
The output of Arrays.toString always has the same shape: square brackets, elements separated by comma and space. You can also use it in String concatenation.
String[] names = {"Ayşe", "Mehmet"};
String text = "Guests: " + Arrays.toString(names);
// Guests: [Ayşe, Mehmet]For nested arrays you use Arrays.deepToString; it also shows multi-dimensional structures neatly. For one-dimensional arrays toString is enough.
Practice Print the week temperatures
Print the given temperature array on one line using Arrays.toString; then print the lowest temperature on a separate line.
Starter code
public class Main {
public static void main(String[] args) {
int[] temps = {22, 18, 25, 19, 21};
// Print the array on one line
// Print the lowest temperature
}
}Sample solution
System.out.println(Arrays.toString(temps));
Arrays.sort(temps);
System.out.println(temps[0]);Expected output
[22, 18, 25, 19, 21] 18
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: print the array
int[] nums = {3, 1, 2};
System.out.println(____);
int[] nums = {3, 1, 2};
System.out.println(Arrays.toString(nums));
Explanation: Arrays.toString(nums) turns the array into text.
2 What does Arrays.toString(new int[]{3, 1, 2}) return?
Arrays.toString(new int[]{3, 1, 2})- "{3, 1, 2}" Correct answer
- "312"
- "[3, 1, 2]"
- void; it prints directly to the console
Explanation: The method returns elements in square brackets separated by commas.
3 Match input to output
| Term | Meaning |
|---|---|
{3, 1, 2} |
[3, 1, 2] |
{10} |
[10] |
{} |
[] |
{"a", "b"} |
[a, b] |