Java Array output

Source: Internet
Author: User

Output an array of elements that we usually do with a for loop, such as:

 Package test;  Public class Test {    publicstaticvoid  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 results of the output are: [1, 2, 3].

But Java provides a much simpler approach, which is the ToString method. The following are the specific practices:

 Package test; Import java.util.Arrays;  Public class Test {    publicstaticvoid  main (String args[]) {        int arr[]={1,2,3};        System.out.println (arrays.tostring (arr));}    }

The results of the output are: [1, 2, 3].

But what if the elements in the array are not the same type? Like what:

 Package test; Import java.util.Arrays;  Public class Test {    publicstaticvoid  main (String args[]) {        int [] arr={1,2,3};        string[] Str={"AAA", "BBB"};          = {arr,str};        System.out.println (arrays.tostring (array));}    }

The result of the output is: [[email protected], [Ljava.lang.string;@79a2e7].

You can see that the print is not an array element, but an object's memory code. What if you want to print an array of elements? Here we can use the deeptostring. Like what:

 Package test; Import java.util.Arrays;  Public class Test {    publicstaticvoid  main (String args[]) {        int [] arr={1,2,3};        string[] Str={"AAA", "BBB"};          = {arr,str};        System.out.println (arrays.deeptostring (array));}    }

Results of the output: [[1, 2, 3], [AAA, BBB]].

Java Array output

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.