Nền Tảng Lập Trình Java: Kiểu Dữ Liệu, Cấu Trúc Rời Rạc và Xử Lý Tập Tin

Quy Trình Biên Dịch và Triển Khai

Java hoạt động theo cơ chế biên dịch sang bytecode trước khi được JVM thực thi. Quy trình cơ bản gồm hai bước: sử dụng công cụ javac để biên dịch mã nguồn thành file lớp, sau đó dùng java để khởi động trình giải thích bytecode.

public class ApplicationDemo {
    public static void main(String[] arguments) {
        System.out.println("Xin chào cộng đồng Java!");
    }
}

Lệnh biên dịch: javac ApplicationDemo.java
Lệnh thực thi: java ApplicationDemo

Hệ Thống Kiểu Dữ Liệu Nguyên Thủy

Java cung cấp tám kiểu dữ liệu nguyên thủy, được chia thành nhóm số nguyên, số thập phân, ký tự và logic. Việc chọn đúng kiểu giúp tối ưu bộ nhớ và hiệu năng.

  • Ký tự: char (16-bit, Unicode)
  • Số nguyên: byte (1 byte, -128~127), short (2 byte, -32,768~32,767), int (4 byte, mặc định), long (8 byte, cần hậu tố L)
  • Số thập phân: float (4 byte, hậu tố f), double (8 byte, mặc định)
  • Logic: boolean (true/false)
public class DataTypeDemo {
    public static void main(String[] args) {
        char symbol = 'Z';
        byte unitCount = 50;
        short shortValue = 1500;
        int standardInt = 9000;
        long largeNumber = 9000000L;
        
        float singlePrecision = 3.14f;
        double doublePrecision = 2.71828;
        boolean isReady = true;
        
        System.out.printf("Char: %c, Byte: %d, Short: %d, Int: %d, Long: %d%n", symbol, unitCount, shortValue, standardInt, largeNumber);
        System.out.printf("Float: %.2f, Double: %.5f, Boolean: %b%n", singlePrecision, doublePrecision, isReady);
    }
}

Nhận Đầu Vào Từ Người Dùng

Hệ thống cung cấp lớp Scanner trong gói java.util để đọc dữ liệu từ luồng chuẩn đầu vào. Cần chú ý dọn dẹp tài nguyên sau khi sử dụng.

import java.util.Scanner;

public class InputHandler {
    public static void main(String[] args) {
        try (Scanner reader = new Scanner(System.in)) {
            System.out.print("Nhập tên đăng nhập: ");
            String username = reader.next();
            
            System.out.print("Nhập số điểm: ");
            int score = reader.nextInt();
            
            System.out.print("Nhập tỷ lệ phần trăm: ");
            double percentage = reader.nextDouble();
            
            System.out.println("Thông tin nhận được: " + username + " | " + score + " | " + percentage + "%");
        }
    }
}

Cơ Chế Vòng Lặp và Hàm Xử Lý

Điều khiển luồng chương trình thông qua whilefor. Các hàm con giúp tái sử dụng mã nguồn, tránh trùng lặp và tuân thủ nguyên tắc DRY. Tên biến không được trùng với từ khóa dành riêng của ngôn ngữ.

public class ControlFlowUtils {
    public static void main(String[] args) {
        int counter = 0;
        while (counter < 5) {
            System.out.println("Lặp while: " + counter);
            counter++;
        }

        for (int i = 0; i < 5; i++) {
            System.out.println("Lặp for: " + i);
        }

        int val1 = 45;
        int val2 = 82;
        System.out.println("Giá trị lớn hơn: " + computeMaximum(val1, val2));
    }

    public static int computeMaximum(int x, int y) {
        return (x > y) ? x : y;
    }
}

Mảng và Thao Tác Chuỗi Ký Tự

Mảng là cấu trúc dữ liệu cố định kích thước. Java hỗ trợ nhiều cách khởi tạo. Chuỗi (String) là đối tượng bất biến, nên các phép cắt, tách đều trả về đối tượng mới. Việc so sánh nội dung chuỗi bắt buộc dùng equals() thay vì == (so sánh tham chiếu).

public class CollectionBasics {
    public static void main(String[] args) {
        float[] tempFloats = new float[3];
        tempFloats[0] = 10.5f; tempFloats[1] = 20.0f; tempFloats[2] = 30.75f;
        
        double[] tempDoubles = {100.1, 200.2, 300.3};
        
        for (double val : tempDoubles) {
            System.out.printf("%.1f ", val);
        }
        System.out.println();

        String rawText = "Alpha,Beta,Gamma,Delta";
        String[] fragments = rawText.split(",");
        for (String part : fragments) System.out.print(part + " ");
        System.out.println();

        String phrase = "Học lập trình hiệu quả";
        System.out.println("Cắt từ vị trí 4: " + phrase.substring(4));
        System.out.println("Cắt đoạn [2,6): " + phrase.substring(2, 6));

        String s1 = "Java";
        String s2 = new String("Java");
        System.out.println("So sánh tham chiếu: " + (s1 == s2));
        System.out.println("So sánh nội dung: " + s1.equals(s2));
    }
}

Danh Sách, Tập Hợp và Bản Đồ

ArrayList cho phép truy xuất theo chỉ số và chèn/xóa linh hoạt. HashSet đảm bảo tính duy nhất của phần tử. HashMap lưu trữ cặp khóa-giá trị, hỗ trợ tra cứu nhanh O(1).

import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;

public class AdvancedCollections {
    public static void main(String[] args) {
        ArrayList<String> roster = new ArrayList<>();
        roster.add("Thành viên A");
        roster.add("Thành viên B");
        roster.add("Thành viên C");
        roster.add("Thành viên D");
        
        for (String member : roster) System.out.println(member);
        
        roster.remove(1); // Xóa theo chỉ số
        roster.set(0, "Trưởng nhóm"); // Thay thế
        roster.add(2, "Thực tập sinh"); // Chèn vào vị trí
        
        System.out.println("--- Sau khi cập nhật ---");
        for (String m : roster) System.out.println(m);

        HashSet<String> uniqueNames = new HashSet<>();
        uniqueNames.add("Nguyễn Văn A");
        uniqueNames.add("Trần Thị B");
        uniqueNames.add("Nguyễn Văn A"); // Bỏ qua trùng lặp
        
        Iterator<String> iter = uniqueNames.iterator();
        while (iter.hasNext()) System.out.println("Set: " + iter.next());

        HashMap scoreBoard = new HashMap<>();
        scoreBoard.put("Đội X", 15);
        scoreBoard.put("Đội Y", 22);
        scoreBoard.put("Đội Z", 10);
        
        System.out.println("Điểm đội Y: " + scoreBoard.get("Đội Y"));
        System.out.println("Có đội W? " + scoreBoard.containsKey("Đội W"));
        
        for (Map.Entry entry : scoreBoard.entrySet()) {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }
    }
}

Quản Lý Tập Tin và Luồng Dữ Liệu

Lớp File cho phép tương tác với hệ thống tệp (kiểm tra tồn tại, duyệt thư mục, xóa). Để đọc/ghi nội dung thực tế, cần kết hợp với FileInputStreamFileOutputStream. Sử dụng buffer giúp tăng tốc độ I/O đáng kể.

import java.io.*;

public class FileSystemManager {
    public static void main(String[] args) throws IOException {
        File targetDir = new File("D:/workspace/logs");
        if (!targetDir.exists()) targetDir.mkdirs();
        
        File dataFile = new File(targetDir, "output.dat");
        System.out.println("Tệp tồn tại: " + dataFile.exists());
        System.out.println("Là thư mục: " + dataFile.isDirectory());
        
        File[] children = targetDir.listFiles();
        if (children != null) {
            for (File child : children) {
                System.out.println("Nội dung thư mục: " + child.getName());
            }
        }

        try (FileOutputStream writer = new FileOutputStream(dataFile)) {
            writer.write("Dữ liệu thử nghiệm Java I/O\n".getBytes("UTF-8"));
        }

        try (FileInputStream reader = new FileInputStream(dataFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            StringBuilder content = new StringBuilder();
            while ((bytesRead = reader.read(buffer)) != -1) {
                content.append(new String(buffer, 0, bytesRead, "UTF-8"));
            }
            System.out.print("Nội dung đọc được: " + content.toString());
        }
    }
}

Ứng Dụng Thực Tế: Phân Tích Tần Suất Từ JSON

Đọc file JSON dạng dòng, trích xuất trường khóa, thống kê số lần xuất hiện và ghi kết quả ra file văn bản. Ví dụ sử dụng thư viện FastJSON để phân tích cú pháp.

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class JsonLogAnalyzer {
    public static void main(String[] args) throws IOException {
        String inputPath = "D:/workspace/data/events.json";
        String outputPath = "D:/workspace/data/report.txt";
        
        HashMap frequencyMap = new HashMap<>();
        
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inputPath), "UTF-8"))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.trim().isEmpty()) continue;
                
                JSONObject record = JSON.parseObject(line);
                String itemId = record.getString("item_id");
                
                frequencyMap.put(itemId, frequencyMap.getOrDefault(itemId, 0) + 1);
            }
        }

        try (FileOutputStream fos = new FileOutputStream(outputPath)) {
            byte[] newLine = System.lineSeparator().getBytes();
            for (Map.Entry entry : frequencyMap.entrySet()) {
                String outputLine = entry.getKey() + " : " + entry.getValue() + "\n";
                fos.write(outputLine.getBytes("UTF-8"));
            }
            System.out.println("Đã thống kê và lưu kết quả vào " + outputPath);
        }
    }
}

Dữ liệu đầu vào mẫu:

{"item_id": "PROD_001"}
{"item_id": "PROD_002"}
{"item_id": "PROD_001"}
{"item_id": "PROD_003"}
{"item_id": "PROD_001"}
{"item_id": "PROD_002"}

Thẻ: Java File I/O Collection Framework JSON Parsing Data Types

Đăng vào ngày 12 tháng 9 lúc 17:32