search
HomeJavajavaTutorialExample analysis of how to use Java arrays

1. Preface

Overview of learning: In the first eight days, we learned the basics of grammar, operators and expressions, loop structures, and branch structures. Today we mainly learn the definition of arrays, related attribute methods, and array storage. Memory diagram, common mistakes

Learning goals: Master the two definition methods of arrays, related properties, understand memory principles, error resolution

2. Definition of arrays

1 .Overview

If the grades of a classmate need to be stored, what method should be used?

As we learned before, multiple variables can be defined to store different scores. But if there are more than 1,000 students, then how about defining more than 1,000 variables? Of course not, this requires using our array.

2. Static initialization of array

Features: Directly assign values ​​to the array when defining it, and the system determines the array length

General format:

Data type [] array name = { element 1, element 2, element 3,... };
For example:
int [] array= {1,2,3,4,5};
double[] scores = {88.5, 99.5, 59.5};

3. Dynamically initialize the array

Features: Determine the type of the element and the length of the array when defining the array, and then Storing data

General format:

Data type[]Array name=new Data type[length];
For example:
int [] array= new int [5];
double[] scores = new double[3];

Default value:

00.0#falseReference typenull

4. Summary

  • Arrays are suitable for large amounts of data of the same type

  • Static initialization is suitable for knowing the element value

  • Dynamic initialization is suitable for unclear data to be stored

3. Array attributes

1. Access

General access The format of the array is:

array name[index]

Example question:

//静态初始化数组
int [] array= {1,2,3,4,5};
System.out.println(array[0]);//输出 1
System.out.println(array[1]);//输出 2
System.out.println(array[3]);//输出 4

2. Length

The length can be called directly length gets the length of the array.

Example question:

//静态初始化数组
int [] array= {1,2,3,4,5};
System.out.println(array.length);//调用方法,输出长度 5
//最大索引array.length-1

3. Traversal

Traversal is accessing array elements one by one, mainly used in search, data statistics...

We have learned about loop structures and branch structures before. Let’s traverse an array through a for loop

Example question:

Given elements {10,8,9,4,5,6,8 ,71,2,3,9,99}, use a static array to store and output elements greater than 5 in the array?

Encoding implementation:

//静态初始化数组
int [] array= {10,8,9,4,5,6,8,71,2,3,9,99};
for(int i=0;i<array.length;i++)
{
	if(array[i]>5)
		System.out.println(array[i]);
}

Output result:

10 8 9 6 8 71 9 99

IV. Memory map

Example analysis of how to use Java arrays

  • When Java runs the program, it needs to allocate space in the memory and divide the space into different areas.

  • Stack memory: stores local variables and disappears immediately after use

  • Heap memory: stores the contents (objects, entities) and addresses of new After use, recycle when the garbage collector is idle

1. Single array memory graph

The following code to create an array implements its memory relationship graph

Encoding implementation:

//动态初始化数组
int [] arr=new int[3];
System.out.println(arr);
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
//修改值
arr[0]=100;
arr[2]=200;
System.out.println(arr);
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);

Output result:

[I@15db9742
0
0
0
[I@15db9742
100
0
200

Principle explanation:

Example analysis of how to use Java arrays

  • Dynamic initialization first generates a new in the heap memory An arr address value, depending on the results of the compiler, assume 001 here. Due to dynamic initialization, each element has an initial value. For details, see the table above. When we output elements, we first access the array name address, go to the heap memory subscript, and then output the element value.

  • To modify the array value, the process is the same as viewing it, except that there is one more step in the modification process, as shown below:

Example analysis of how to use Java arrays

2. Multiple array memory diagram

Example analysis of how to use Java arrays

The principle of using multiple arrays and single array memory is the same, so I won’t go into details here.

3. The arrays point to the same memory

If we change the address values ​​of the two arrays to be the same, what will the modified result be like, as shown in the following code.

Encoding implementation:

//动态初始化数组
int [] arr=new int[3];
arr[0]=100;
arr[1]=200;
arr[2]=300;
System.out.println(arr);
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
int [] arr2=arr;
arr2[0]=111;
arr2[1]=222;
arr2[2]=333;
System.out.println(arr);
System.out.println(arr[0]);
System.out.println(arr2);
System.out.println(arr2[0]);

Output result:

[I@15db9742
100
200
300
[I@ 15db9742
111
[I@15db9742
111

Principle explanation:

Example analysis of how to use Java arrays

##The first array is in the heap memory The address of is 001, and the second array is also 001, so modifying the value of the second array is actually the same array memory. The value of the first array will also change accordingly, and the result is as follows:

Example analysis of how to use Java arrays

5. Frequently Asked Questions

1. Index out of bounds

//静态初始化数组
int [] array= {1,2,3};
System.out.println(array[3]);

  • After the above code is run, the following error exception will appear:

  • Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

  • Explanation: We statically initialized the array and gave it 3 numbers. The maximum index is 2. When we access 3, an error will be reported.

2. Null pointer Exception

//动态初始化数组
int [] array= new int[3];
array=null;
System.out.println(array[0]);

  • After the above code is run, the following error exception will appear:

  • Exception in thread "main" java.lang.NullPointerException

  • Explanation: We set the array to null, causing the array accessed not to point to the data in the heap memory

Data type Specific definition type Default value
Basic type ##byte, short, char, int, long

float,double

boolean

Class, interface, array, String

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

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
ZipInputStream failed to decompress Chinese file name? How to set the character set correctly?ZipInputStream failed to decompress Chinese file name? How to set the character set correctly?Apr 19, 2025 pm 04:33 PM

Discussion on ZipInputStream character set settings Many developers use ZipInputStream to decompress zip compressed packages containing Chinese file names or folder names, �...

How to implement a retry strategy from serverB to serverC using Spring WebFlux when building LLM gateway?How to implement a retry strategy from serverB to serverC using Spring WebFlux when building LLM gateway?Apr 19, 2025 pm 04:30 PM

Implementing the retry strategy using SpringWebFlux in building an LLM...

How to ensure that @Scheduled timing tasks are executed only once in Spring Boot multi-node environment?How to ensure that @Scheduled timing tasks are executed only once in Spring Boot multi-node environment?Apr 19, 2025 pm 04:21 PM

How to avoid repeated execution of timed tasks in SpringBoot multi-node environment? In Spring...

In object-oriented programming: Are attributes and states really equivalent?In object-oriented programming: Are attributes and states really equivalent?Apr 19, 2025 pm 04:18 PM

Deeply discussing properties and states in object-oriented programming. In object-oriented programming, the concepts of properties and state are often confused, and there is a subtle between them...

How to deal with a number overflow error when connecting to Oracle database in IDEA?How to deal with a number overflow error when connecting to Oracle database in IDEA?Apr 19, 2025 pm 04:15 PM

How to deal with digital overflow errors when connecting to Oracle database in IDEA When we are using IntelliJ...

How to use @ResultType annotation correctly in MyBatis?How to use @ResultType annotation correctly in MyBatis?Apr 19, 2025 pm 04:12 PM

When studying the MyBatis framework, developers often encounter various problems about annotations. One of the common questions is how to use the @ResultType annotation correctly...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool