Arrays in Java arrays are an extremely important object, using a single variable to store multiple values of the same data type.
1. Array declaration (Declaring)
Syntax example:
1 2 3 | int[] ages; int ages[]; |
Including 3 components are:
- Data types: int (eg String, double, float, …).
- Variable name: ages.
- Square brackets: [].
2. Create and initialize arrays (Creating, Initializing).
- Create (Creating):
Syntax example:
123int[] ages = new int[10];int ages[] = new int[10];The above syntax makes sense to create an array with 10 elements, in other words the ages variable can store 10 values.
- Initializing:
Syntax example (1 way):
123int[] ages = {1, 2, 3, 4, 5, 6};int ages[] = {1, 2, 3, 4, 5, 6};The above initialization syntax is meant to initialize 6 elements and have values from 1 – 6. Syntax example (2-way):
123int[][] board = {{1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}};int board[][] = {{1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}};Syntax example (3 dimensional):
123int[][][] board = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};int board[][][] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
3. Access (Accessing).
Syntax example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Khởi tạo một mảng ages; int[] ages = {1, 2, 3, 4, 5, 6}; // Truy xuất phần tử: // Truy xuất giá trị phần tử đầu tiên của mảng: ages[0]; // giá trị 1 // Truy xuất giá trị phần tử cuối cùng của mảng: ages[5]; // giá trị 6 // Gán một giá trị vào phần từ: // Gán giá trị vào phần tử đầu tiên của mảng: ages[0] = 8; // Gán giá trị vào phần tử cuối cùng của mảng: ages[5] = 9; |
4. Example of array:
A piece of code that interacts with an array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import java.util.Scanner; public class AJS_1 { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { // Tao mang co ten ages int[] ages = new int[3]; // Gan gia tri cac phan tu mang System.out.println("Nhap 3 so nguyen vao mang: "); ages[0] = Integer.parseInt(scanner.nextLine()); ages[1] = Integer.parseInt(scanner.nextLine()); ages[2] = Integer.parseInt(scanner.nextLine()); // Truy xuat gia tri phan tu mang System.out.println("Cac gia tri phan tu trong mang: "); System.out.println(ages[0]); System.out.println(ages[1]); System.out.println(ages[2]); } } |
In the Series I will introduce the basic knowledge that I have learned, and based on it to offer problems and how to solve problems.
If anything goes wrong, please comment.