Home > Java > javaTutorial > How to use arrays in Java?

How to use arrays in Java?

WBOY
Release: 2023-04-26 12:13:07
forward
662 people have browsed it

Use a simple array

(1)Create a class named T04 and declare two variables array1 and array2 in the main() method

They are arrays of type int[] .

(2) Use curly brackets {} to initialize array1 to 8 prime numbers: 2, 3, 5, 7, 11, 13, 17, 19.

(3) Display the contents of array1.

(4) Assign array2 variable equal to array1, modify the even index element in array2 to make it equal to the index value (such as array[0]=0, array[2]=2). Print out array1. **Thinking: What is the relationship between array1 and array2?
Extension: Modify the question to realize the copying of array1 array by array2

public class T04 {
    public static void main(String[] args) {
        int[] array1,array2;
        array1=new int[]{2,3,5,7,11,13,17,19};
        for(int i=0;i< array1.length;i++){
            System.out.print(array1[i]+"\t");
        }     //赋值array1变量等于array2     //不能称作数组的复制
        array2=array1;
        for(int i=0;i< array1.length;i++){
            if(i%2==0){
                array2[i]=i;
            }
        }
        System.out.println();
        System.out.println("******************************************");
        for(int i=0;i< array1.length;i++){
            System.out.print(array1[i]+"\t");
        }
    }
}
Copy after login

How to use arrays in Java?

(1) The addresses of array1 and array2 The values ​​are the same, and they all point to the only array entity in the heap space

(2)

 for(int i=0;i< array1.length;i++){
            array2[i]=array1[i];
        }
Copy after login

How to use arrays in Java?

Method 2

int i=0;
        int j=0;
        for(i=0,j= arr.length-1;i<j;i++,j--){
            int a=arr[i];
            arr[i]=arr[j];
            arr[j]=a;
        }
Copy after login

The above is the detailed content of How to use arrays in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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