Table of Contents
1. Preface
2. Definition of arrays
1 .Overview
2. Static initialization of array
3. Dynamically initialize the array
4. Summary
3. Array attributes
1. Access
2. Length
3. Traversal
IV. Memory map
1. Single array memory graph
2. Multiple array memory diagram
3. The arrays point to the same memory
Home Java javaTutorial Example analysis of how to use Java arrays

Example analysis of how to use Java arrays

May 10, 2023 pm 05:19 PM
java

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
Copy after login

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
Copy after login

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]);
}
Copy after login

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]);
Copy after login

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]);
Copy after login

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]);
Copy after login

  • 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]);
Copy after login
  • 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 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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles