search
HomeJavajavaTutorial[Java Getting Started Notes] Java Language Basics (5): Arrays

Introduction

Arrays can be used to store multiple data. Java arrays require that all array elements have the same data type. Once the array is initialized, the space in the memory of the array is fixed and the length cannot be changed. Even if the elements of the array are cleared, the space occupied is still retained.

Lifestyle Case: Museum Rack

[Java Getting Started Notes] Java Language Basics (5): Arrays

Each item rack contains the same type of items, and the length remains unchanged. Even if the items are removed from the shelf, the item rack will not change.

Define an array

[Java Getting Started Notes] Java Language Basics (5): Arrays

4 steps to use an array:

1. Declare an array

Java supports two formats of array definition format:

type [] variable name; Type variable name[];

Example:

int[] a;int b[]; //Both methods will work, but it is recommended to use the first one.

Declaring an array is equivalent to purchasing a customized item rack (array) in the museum in the above example, but the size of the item rack (array size) has not yet been determined, nor has anything been placed on the item rack. (array element).

2. Allocate space

Allocating space is to initialize the array. There are two ways to initialize:

The first one: static initialization

The syntax format of static initialization is as follows:

Data type [] variable name = new data type []{data 1, data 2, data 3,...};

Example:

int[] a = new int[]{4,2,64,12,3}; //Store these numbers in an array. The size (length) of the array is the number of elements in the curly braces. In this example, the size is 5String[] b = new String[]{"Zhang San", "Li Si", " Wang Wu"}; //The type of all data must be the defined data type int[] c = {2,5,7}; //You can also use this abbreviation

This is like buying a customized The item rack comes back, and the display items are placed in the item rack and purchased together. The items will be as large as the size of the item rack.

Second type: Dynamic initialization

Dynamic initialization is a way to only specify the size of the array and let the system specify the initial value for each element. The syntax format is as follows:

data type [] variable name = new data type [size];

In this format, you need to specify an array size of integer type. After specifying, the length of the data and array will be determined. How many elements can be stored. Also assigns a default initial value to all elements.

Example:

int[] a = new int[5]; //Define an array with a length of 5, that is to say, it can store 5 int type data. At the same time, the default 5 values ​​​​are initialized to 0

Default values ​​during initialization are set as follows:

byte, short, int, long default to 0;

float, double default to 0.0;

char defaults to 'u0000';

boolean defaults to false;

Other reference types default to null;

3. Assignment

Although you have initialized the array, we can still change the data inside by assignment. So the array has been initialized and the size of the array has been determined. How do we assign a value to each array element?

There is also a concept of subscript in the array. When the array is initialized, each element will be assigned a subscript, just like the number on the item display shelf. We can reassign a value to each element through the subscript.

The subscript of the array starts from 0, that is to say, the subscript of the first element is 0. As for why it starts from 0, we will discuss it later. Let’s first look at the example of assignment:

int[] a = new int[3]; //Define an int type array with a length of 3, in which the three element values ​​have defaulted to 0; a[0] = 4; //Set the first element value to 4a[1] = 5; //Set the second element value to 5a[2] = 7; //Set the third element value to 7

[Java Getting Started Notes] Java Language Basics (5): Arrays

Why does the array subscript start from 0?

The first thing we need to know is that the program runs in the computer memory. When our program starts to process data, a small space will be opened in the memory to store the data. In the code, a variable is defined. , such as:

int a = 5;

Define an int type variable with a value of five, which is expressed in memory as, allocate a small piece of memory in the memory, named a, and the value stored in it is 5.

[Java Getting Started Notes] Java Language Basics (5): Arrays

And how do we get the value in memory through a variable name like a? It's because every small piece of memory has an address, just like the home we live in has an address. Through this address, we can know who lives in it.

Two arrays are stored in connected locations in memory to facilitate array operations. Let’s look at an example:

int[] b = new int[3]; //Define an array of type int with a length of 3. The default value of the elements inside is 0

At this time, the memory is like this:

[Java Getting Started Notes] Java Language Basics (5): Arrays

The same is true for obtaining data in the array. How to know the data of each element of the b array? First of all, we know where the array b is in the memory. Because the array is a connected memory space in the memory, the position of b[0] is equal to b+0, and the position of b[1] is b+ 1,b[2]=b+2,... and so on, we know the positions of all elements of the array. The first element in the array is exactly at the beginning of the array. If it is represented by b[0], it is exactly the position represented by b. If 1 is used to represent the position of the first element, it needs to be expressed as a+1- 1.

4. Processing data

In the previous content, we have defined the array, initialized the array, and assigned values. So how to use the data? In fact, we have already analyzed it before. We assign values ​​to the array through array subscripts. The value of each array element is also obtained through the array subscript.

int[] a = new int[3]; a[0] = 3; a[1] = 4; a[2] = 5; System.out.println(a[1]); //Get the value of the second position of the array and output it //We can also loop through each element in the array for(int i = 0; i

In the above example, when looping to print, we see that a.length is used, through the array The variable name .length can get the length of the array, so above we use a.length to get the length of the array to be 3, loop 3 times, and print out the elements of the array.

You should not access non-existent subscripts

As we know above, we control the array by assigning or getting a value to the variable through the variable name [subscript], and if the access exceeds the subscript of the array length, it will appear abnormal.

int[] a = new int[2]; a[5] = 2; //The length of the a array is only 2 lengths, and we access the 6th element through subscript 5. If this position does not exist in the a array, an exception will occur.

Two-dimensional array or multi-dimensional array

What we talked about above is to store a basic data type or reference data type in an array, and we can also store an array in an array:

[Java Getting Started Notes] Java Language Basics (5): Arrays

Above We store another array element in an array element, and the array inside stores a value of data type int. We call such an array a two-dimensional array.

Definition, initialization and assignment of two-dimensional array

Data type [ ] [ ] Array name = new Data type [length 1] [length 2] ;

Length 1 is the length of the outer layer of array, length The length of one layer inside 2 digits.

To define and initialize the form in the picture above, we can do this:

int[][] a = new int[3][3]; a[0][0] = 2; //When accessing, the number in the first square bracket represents the element subscript of the outer layer of the array, and the number in the second square bracket represents the subscript of the inner layer of the array a[0 ][1] = 3; a[0][2] = 4; a[1][0] = 5; a[1][1] = 3; a[1][2] = 9; a[2][0] = 90; a[2][1] = 70; a[2][2] = 85;

We can also define the two-dimensional array in such a format:

[Java Getting Started Notes] Java Language Basics (5): Arrays

int[][] a = new int[3][ ]; //Set the length of the outer layer to 3 when defining initialization, and do not set the length of the inner layer,
a[0] = new int[2]; //Initialize each layer inside, and set the length a[1] = new int[1]; a[2] = new int[3]; a[0][0] = 3; //Assign a value to each element a[0][1] = 4; a[1][0] = 9; a[2][0] = 90; a[2][1] = 70; a[2][2] = 85;


A three-dimensional array is an array inside an array that stores an array~~~~~ By analogy, there can be n multi-dimensional arrays, but most people don’t use them much ~~~^_^~~~

The above is [Introduction to Java Notes] Java Language Basics (5): Contents of Arrays. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
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
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

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

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 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.