SoFunction
Updated on 2025-05-07

Java array (Array) to store data "row" (latest recommendation)

Hello everyone! 👋 When we are programming, we often need to process a batch of data of the same type, such as the grades of all students in the class, the maximum temperature per day of the week, 🌡️, or the product list in the shopping cart 🛒. If a separate variable is declared for each data (score1, score2, score3…), then the code must not be written "crazy"? 🤯

At this time, it is the turn of a basic and important data structure in Java to come on the stage-Array(Array)! You can think of it as a row of numbered lockers or an egg tray 🥚, specially designed to store neatlyMultiple same typedata. Today, let’s fully understand the “old friend” of the array!

1. What exactly is an array? 🤔

Simply put, an array is oneFixed sizecontainer 📦, elements stored in itMust be the same data type.

Several key features to remember:

  • Uniform type:oneintOnly put in the arrayint,oneStringOnly put in the arrayString. Can't mix it up! 🚫
  • Fixed length: Once an array is created, its length (how many elements can be installed) cannot be changed! This is one of the most core limitations of the array ⚠️.
  • Continuous storage(usually): In memory, elements of an array are usually stored continuously, which makes access to elements through indexes very fast ⚡️.
  • Index access: Each element has a unique index (number), from0start! Elements can be quickly positioned and accessed through indexes.

2. Create and use arrays ✍️

How to use arrays in code? It is mainly divided into two steps:statementandinitialization

2.1 Declare array references

Tell the compiler: "I want a variable that can point to an array of some type".

// Recommended declaration methodint[] scores;
String[] names;
double[] prices;
// C/C++ style declaration method (can also be used, but not recommended)// int scores[];
// String names[];

Note: This is just a reference variable declared, it is stillnull, does not point to any actual array memory space.

2.2 Initialize array (allocate space/assign value)

Initialization is the time to really create array objects and allocate memory space. There are two main ways:

Method 1: UsenewSpecify length

This is the most commonly used method. You know how big the array is needed, but you are not sure about the specific value inside it.

// Create an array that can store 5 intsscores = new int[5]; // 5 int spaces were allocated// Create an array that can store 10 Stringsnames = new String[10]; // Allocated 10 String reference spaces// Declaration and initialization can be mergeddouble[] salaries = new double[50];

Focus📌: UsenewAfter creating an array, the elements inside will be automatically assigned todefault value

  • Numeric type (int, double etc.):0or0.0
  • boolean: false
  • char: \u0000(empty characters)
  • Reference type (String, Object etc.):null

Method 2: Static initialization (directly provide element values)

If you already know which elements to put in when creating an array, you can use this simpler way. The compiler will automatically determine the length of the array based on the values ​​you provide.

// Provide the initial value directly, the length is determined by the compiler (here is 4)int[] initialScores = {90, 85, 92, 78};
// Merge declaration and static initializationString[] weekdays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
// Can't write separately!  The following is wrong ❌// int[] numbers;
// numbers = {1, 2, 3}; // Compile error// It must be written like this:int[] numbers;
numbers = new int[]{1, 2, 3}; // Or initialize when declared

2.3 Accessing array elements: rely on indexing[] 👉

The core operation of an array is to access elements through indexes. remember:The index starts at 0!Very, very important! 🚨

public class ArrayAccess {
    public static void main(String[] args) {
        String[] fruits = {"Apple &lt;🍎&gt;", "Banana &lt;🍌&gt;", "Orange &lt;🍊&gt;"}; // Length is 3        // Access elements (index 0, 1, 2)        ("First fruit: " + fruits[0]); // Apple <🍎> (Index 0)        ("Second fruit: " + fruits[1]); // Banana <🍌> (Index 1)        ("Third fruit: " + fruits[2]); // Orange <🍊> (Index 2)        // Modify elements        fruits[1] = "Grape &lt;🍇&gt;"; // Change the second element (index 1) to Grape        ("Second fruit now: " + fruits[1]); // Grape &lt;🍇&gt;
        // Try to access an index that does not exist?  The consequences are serious!        // (fruits[3]); // Runtime error💥: ArrayIndexOutOfBoundsException    }
}

2.4 Get the array length:.lengthProperties 📏

Want to know how much stuff can be installed in an array? use.lengthproperty(Note: It is an attribute, not a method, there are no brackets afterwards(), this andStringoflength()Different methods are easy to confuse! ).

int[] data = new int[10];
("Length of data array: " + ); // Output: 10
String[] colors = {"Red", "Green", "Blue"};
("Number of colors: " + ); // Output: 3

.lengthEspecially useful when looping through arrays.

3. Traverse the array: "name" one by one 🚶‍♀️🚶‍♂️

To traverse an array is to access each element in the array in order, usually implemented in a loop.

3.1 Using traditionforcycle

The most flexible way is because you can get the current indexi

public class ForLoopArray {
    public static void main(String[] args) {
        double[] readings = {12.5, 13.1, 11.8, 12.9};
        ("Sensor Readings:");
        // The cycle conditions are usually i <        for (int i = 0; i &lt; ; i++) {
            ("Reading at index " + i + ": " + readings[i]);
        }
    }
}

3.2 Using EnhancedforLoop (for-each)

If you don't need to care about indexes, just want to process each element in sequence, this method is simpler and easier to read.

import ; // Just to demonstrate collection traversalimport ;
public class ForEachArray {
    public static void main(String[] args) {
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        ("Vowels: ");
        // Take out each char in the vowels array and assign it to the variable vowel        for (char vowel : vowels) {
            (vowel + " ");
        }
        (); // Output: a e i o u        // Also applicable to collections (such as ArrayList)        // List&lt;String&gt; names = new ArrayList&lt;&gt;(); ...
        // for (String name : names) { ... }
    }
}

How to choose?If you need an index (such as modifying an element based on the index, or you need to know which element is currently), use traditionalfor. If you just read the value of each element, the enhanced typeforUsually better.

4. "Common Troubles" of Arrays 😩💥

There are several classic errors you are likely to encounter when using arrays:

  • ArrayIndexOutOfBoundsException<💥>: This is the most common array error! When you try to access an index that does not exist (such as index < 0, or index >=), this runtime exception will be thrown. Be especially careful when writing loops!
  • NullPointerException: If your array reference variable itself isnull(i.e. it does not point to any array object), and you are trying to access it.lengthAttributes or access elements through indexes (e.g.nullArray[0]), you will get this runtime exception.
  • Before using the array, make sure it has been initialized correctly!The length is fixed<🔒>: As mentioned earlier, once the array length is determined, it cannot be changed. If your program needs a container that can dynamically add and delete elements, then the Java collection frameworkArrayListClasses like this are usually better choices.

5. Beyond the basics: multi-dimensional array and Arrays tool class ▦🛠️

5.1 Multidimensional array

You can create "arrays of arrays", most commonly a two-dimensional array, which you can think of as a table or matrix ▦.

// Create an int 2D array with 3 rows and 4 columnsint[][] matrix = new int[3][4];
// Static initializationString[][] board = {
    {"X", "O", "X"},
    {"O", "X", "O"},
    {"X", "O", "X"}
};
// Two indexes are required to access elementsmatrix[0][1] = 5; // Set row 1 and column 2 (the indexes start from 0)("Board[1][1]: " + board[1][1]); // Output: X

It usually requires nested loops to traverse a two-dimensional array.

5.2 Tools <🛠️>

Java provides a very useful oneArraysClass (inPackage), contains many operand arraysstaticMethods can save a lot of trouble:

  • (array): Convert arrays into easy-to-read strings for easy printing and debugging. It is highly recommended! 👍
  • (array): Sort the array (sort in place).
  • (array, value): Fill the entire array with the specified value.
  • (originalArray, newLength): Copy part or all of the original array to a new array (can be used to "extend" the array in disguise).
  • (array1, array2): Compare whether the contents of two arrays are equal (note, not using==compare address).
import ; // <--- Don't forget to import!public class ArraysUtilDemo {
    public static void main(String[] args) {
        int[] nums = {5, 2, 8, 1, 9};
        // Good-looking printing method        ("Original array: " + (nums));
        // Sort        (nums);
        ("Sorted array: " + (nums));
        // Fill        int[] filled = new int[5];
        (filled, -1);
        ("Filled array: " + (filled));
        // Copy (take the first 3 elements)        int[] copied = (nums, 3); // nums is already sorted {1, 2, 5, 8, 9}        ("Copied first 3: " + (copied));
    }
}

6. Summary 🏁

Arrays are the basic data structures in Java that store fixed number of elements of the same type.

  • Core features: Unified type, fixed length, index access (starting from 0).
  • How to createnew Type[size]Or static initialization{...}
  • Access and Length:usearray[index]access,.lengthGet the length.
  • Traversal: Commonly usedforOr enhanceforcycle.
  • Common Traps 🚨:ArrayIndexOutOfBoundsException, NullPointerException, length fixed limit.
  • Good helper <🛠️>:The class provides many practical methods.

AlthoughArrayListCollection classes are better in flexibility, but arrays still have their advantages in performance (especially access speed) and representing fixed-size datasets, and are the basis for understanding collection classes. Therefore, it is very important to master the arrays in a solid manner!

7. Practice your hands and test the results! ✏️🧠

Come on, write the code and consolidate it!

⭐ Basic Operation ⭐

  • Declare one can store 10doubleArray of type dataprices, and initialize all its elements into9.99(Use loop or)。
  • Create aStringArraycolors, including "Red", "Green", "Blue", "Yellow". Then, modify the third element ("Blue") to "Purple", and print the modified array contents (using)。

⭐ Loop and Calculation ⭐

  • Given oneintArrayscores = {88, 92, 75, 98, 85}, calculate and print the average of all fractions in the array (note that the result may be a decimal).
  • Find an arrayint[] data = {5, -2, 9, 15, -8, 1}and print it out.

⭐ Concept Analysis ⭐

  • Try to explain why the index of an array starts at 0 instead of 1? (Tip: You can think from the perspective of memory address and offset, or explain its historical origin and programming habits)
  • Compare arrays (int[]) andArrayList<Integer>The main differences, especially in size and type.

8. Reference answer ✅💡

⭐ Basic operation answers ⭐

1. InitializationpricesArray:

import ;
public class InitPrices {
    public static void main(String[] args) {
        double[] prices = new double[10];
        // Method 1: Use loop        // for (int i = 0; i &lt; ; i++) {
        //     prices[i] = 9.99;
        // }
        // Method 2: Use (more recommended)        (prices, 9.99);
        ("Initialized prices: " + (prices));
    }
}

2. ModifycolorsArray:

import ;
public class ModifyColors {
    public static void main(String[] args) {
        String[] colors = {"Red", "Green", "Blue", "Yellow"};
        ("Original colors: " + (colors));
        // The third element index is 2        if ( &gt; 2) { // Make a simple check to prevent crossing the line            colors[2] = "Purple &lt;💜&gt;";
        }
        ("Modified colors: " + (colors));
        // Output: Modified colors: [Red, Green, Purple <💜>, Yellow]    }
}

⭐ Loop and Calculate Answers ⭐

3. Calculate the average score:

import ;
public class AverageScore {
    public static void main(String[] args) {
        int[] scores = {88, 92, 75, 98, 85};
        if ( == 0) {
            ("Array is empty, cannot calculate average.");
            return;
        }
        int sum = 0;
        for (int score : scores) {
            sum += score;
        }
        // Note: In order to get exact decimal results, you need to convert sum or length to double        double average = (double) sum / ;
        // Or double average = sum * 1.0 /;        ("Scores: " + (scores));
        ("Average score: " + average); // Output: Average score: 87.6    }
}

4. Find the maximum value:

import ;
public class FindMaxValue {
    public static void main(String[] args) {
        int[] data = {5, -2, 9, 15, -8, 1};
        if ( == 0) {
            ("Array is empty.");
            return;
        }
        int max = data[0]; // Assume that the first element is the maximum value        for (int i = 1; i &lt; ; i++) {
            if (data[i] &gt; max) {
                max = data[i]; // If larger one is found, update max            }
        }
        ("Data: " + (data));
        ("Maximum value: " + max); // Output: Maximum value: 15    }
}

⭐ Concept Analysis Answer ⭐

5. Why does the index start at 0?

This is mainly due to historical reasons and considerations of underlying implementation efficiency. In C languages ​​(an important ancestor of Java) and earlier, array names usually represent the starting address of the first element of the array in memory. Access array elementsarray[i], actually calculationStart address + i * Size of each elementCome find thei+1address of each element. If the index starts at 0, access the first elementarray[0]that isStart address + 0 * size, that is, the starting address itself, the simplest and most efficient calculation. If starting from 1, access the first elementarray[1]It needs to be calculatedStart address + (1-1) * size, one more step subtraction. This index starting from 0 (calledzero-based indexing) has become a programming convention for the C family languages ​​(including C++, Java, C#, JavaScript, etc.).

6.int[] vs ArrayList<Integer>the difference:

  • size:
    • int[]: Fixed size. Once created, the length cannot be changed.
    • ArrayList<Integer>: The size is variable. Elements can be added or removed dynamically, and their internal capacity will be automatically adjusted (although performance overhead may be involved).
  • type:
    • int[]: The basic data type is storedintvalue.
    • ArrayList<Integer>: The storage is a packaging class<font color="purple">Integer</font>object reference. It cannot directly store basic typesint(But Java's automatic boxing/unboxing mechanism makes it very similar to using itint)。
  • Function: ArrayListMore ready-made methods are provided (e.g.add, remove, contains, sizeetc.), while array functions are relatively basic (mainly relying on index andArraysTools).
  • performance: For fixed-size and frequently accessed scenarios, arrays are usually moreArrayListSlightly better performance (especially for primitive type arrays, avoiding the overhead of packing/unboxing and object references).

I hope this note on arrays can help you lay a solid foundation! Once you use it, you will feel much more relaxed when you look at the collection framework! If it helps, don't forgetLike 👍, favorite ⭐, followoh! grateful! 💖

This is the article about Java Basics - Array: "Sitting in a row" for storing data. For more related Java array Array content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!