Java array output instance code
- 2020-04-01 02:38:20
- OfStack
Output an array of elements, we usually use the for loop to do, such as:
package test;
public class Test {
public static void main(String args[]){
int arr[]={1,2,3};
System.out.print("[");
for(int i=0; i<arr.length-1; i++)
System.out.print(arr[i]+", ");
System.out.println(arr[arr.length-1]+"]");
}
}
The output result is: [1, 2, 3].
But Java offers an even simpler method, the toString method. The specific approach is as follows:
package test;
import java.util.Arrays;
public class Test {
public static void main(String args[]){
int arr[]={1,2,3};
System.out.println(Arrays.toString(arr));
}
}
The output result is: [1, 2, 3].
But what if the elements in the array are not of the same type? Such as:
package test;
import java.util.Arrays;
public class Test {
public static void main(String args[]){
int[] arr={1,2,3};
String[] str={"aaa","bbb"};
Object[] array = {arr,str};
System.out.println(Arrays.toString(array));
}
}
The output is: [[i@158f9d3, [ljava.lang.string;@79a2e7].
You can see that instead of an array element, the memory code for the object is printed. What if I want to print out an array element? We can use deepToString here. Such as:
package test;
import java.util.Arrays;
public class Test {
public static void main(String args[]){
int[] arr={1,2,3};
String[] str={"aaa","bbb"};
Object[] array = {arr,str};
System.out.println(Arrays.deepToString(array));
}
}
Output results: [[1, 2, 3], [aaa, BBB]].