Giới thiệu về Java
Jim White
Java Developer


[]// Khai báo biến mảng int[] prices;// Gán giá trị prices = {10, 20, 30, 40};

[]:int[] prices = {10, 20, 30, 40};
// Truy cập phần tử đầu tiên
int firstElement = prices[0]; // Giá trị là 10
// Truy cập phần tử thứ hai
int secondElement = prices[1]; // Giá trị là 20

int[] prices = {10, 20, 30, 40};// Đổi giá trị phần tử thứ ba thành 95 prices[2] = 95;

int[] itemIDs = {10, 20, 30, 40, 50};
// Truy cập phần tử thứ sáu không tồn tại
itemIDs[5] = 60; // <- Sẽ gây lỗi
.lengthint[] prices = {10, 20, 30, 40};
int pricesLength = prices.length; // Giá trị là 4

Ta có thể in từng giá trị:
class ArrayElementPrinting {
public static void main (String[] args){
int[] prices = {10, 20, 30, 40};
// In từng phần tử
System.out.println(prices[0]);
System.out.println(prices[1]);
}
}
10
20
In cả mảng trả về dạng biểu diễn:
class ArrayPrinting {
public static void main (String[] args){
int[] prices = {10, 20, 30, 40};
// In toàn bộ mảng
System.out.println(prices);
}
}
[I@d041cf
// Mảng String
String[] productNames = {"Organic Honey",
"Cold Brew Coffee",
"Dark Chocolate Bar"};
Strings
// Khai báo và gán
int[] prices = {10, 20, 30, 40};
// Lấy giá trị
int secondElement = prices[1];
// Cập nhật
prices[1] = 25;
// Độ dài
// Giá trị là 4
int pricesLength = prices.length;
Giới thiệu về Java