Operation of the Java array

Source: Internet
Author: User

1. Gets all the elements in the array, using the array traversal

The traversal of an array, usually with a for loop.

 Public class Arraydemo {    publicstaticvoid  main (string[] args) {        int  newint[3];          for (int i=0;i<arr.length;i++)        // the array name is the length of the array. The minimum value of the array's angular index is 0, and the maximum value is length-1.          {            System.out.println (arr[i]);     }}}

Output:

0
0
0

2. Find the sum of the numbers in the array

 Public class Arraydemo {    publicstaticvoid  main (string[] args) {        int [] arr = {22,3,5,6,81,};         int sum=0;          for (int i=0;i<arr.length;i++)        {            + =arr[i];        }        SYSTEM.OUT.PRINTLN (sum);}    }

Output: 117

3. Print out all the elements in the array and use "," to separate

 Public classArraydemo { Public Static voidMain (string[] args) {int[] arr = {22,3,5,6,81,};                            Printarr (arr); //calling Functions    }     Public Static voidPrintarr (int[] arr) {//a function that defines an output array.          for(inti=0;i<arr.length;i++)        {            if(I>=0 & I<arr.length-1)//The output array element that is not the last element is judged, and a comma is added. Can be written i!=arr.length-1System.out.print (arr[i]+ ","); Else{//last element, output element only, no commaSystem.out.print (Arr[i]); }        }    }}

Output:

22,3,5,6,81

Operation of the Java array

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.