Giới thiệu
Ví dụ đơn giản minh họa cách đảo ngược chuỗi ký tự (reverse string) nhập từ EditText và hiển thị lên TextView sử dụng StringBuffer.reverse().
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
Bước 2: Giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="Nhập tên"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button android:id="@+id/save" android:text="Lưu"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Bước 3: MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText name;
TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
textview = findViewById(R.id.textview);
findViewById(R.id.save).setOnClickListener(v -> {
String input = name.getText().toString();
if (!input.isEmpty()) {
// Cách 1: StringBuffer (thread-safe, cũ)
StringBuffer buffer = new StringBuffer(input);
textview.setText(buffer.reverse().toString());
// Cách 2: StringBuilder (khuyên dùng, nhanh hơn, không thread-safe)
// StringBuilder builder = new StringBuilder(input);
// textview.setText(builder.reverse().toString());
// Cách 3: Java 8+ Stream (ngắn gọn)
// textview.setText(new StringBuilder(input).reverse().toString());
Toast.makeText(this, "Đã đảo ngược", Toast.LENGTH_LONG).show();
} else {
name.setError("Nhập tên");
}
});
}
}
So sánh StringBuffer vs StringBuilder
| Đặc điểm | StringBuffer | StringBuilder |
|---|---|---|
| Thread-safe | Có | Không |
| Hiệu năng | Chậm hơn | Nhanh hơn |
| Khuyên dùng | Đa luồng | Đơn luồng (UI thread) |
Trong Android UI chạy trên main thread, nên dùng StringBuilder cho hiệu năng tốt hơn.
Chạy ứng dụng

Ví dụ: Nhập "Android" → Kết quả "diordnA".