Home > Java > JavaBase > body text

What are the methods of assigning values ​​to arrays in java?

王林
Release: 2019-11-21 16:42:50
Original
17344 people have browsed it

What are the methods of assigning values ​​to arrays in java?

1. Direct assignment

arr[0]=1;      0代表的是数组的第1个元素 ,元素下标为0
arr[1]=1;      1代表的是数组的第2个元素 ,元素下标为1
Copy after login

2. Use for loop assignment

 int[ ]  arr=new int[5];     
 for (int i = 0; i < arr.length; i++) {
            System.out.println("数组第"+(i+1)+"个值为"+i);
         }
Copy after login

Result:

What are the methods of assigning values ​​to arrays in java?

3. Use loop traversal to assign values ​​to the array

 int[ ] arr={1,3,6,5,6,7,84,55,5};  
 for (int num:arr) {
      System.out.println(num);
  }
Copy after login

Result:

What are the methods of assigning values ​​to arrays in java?

Recommended tutorial: Java introductory tutorial

The above is the detailed content of What are the methods of assigning values ​​to arrays in java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!