Table of Contents
1. Truyền giá trị (pass by value) trong Java
Nếu chúng ta gọi một phương thức và truyền một giá trị cho phương thức đó được gọi là truyền giá trị. Việc thay đổi giá trị chỉ có hiệu lực trong phương thức được gọi, không có hiệu lực bên ngoài phương thức.
Ví dụ giá trị data không bị thay đổi sau khi gọi phương thức change():
class Operation {
int data = 50;
void change(int data) {
data = data + 100; // changes will be in the local variable only
}
public static void main(String args[]) {
Operation op = new Operation();
System.out.println("before change " + op.data);
op.change(500); // passing value
System.out.println("after change " + op.data);
}
}
Kết quả:
before change 50 after change 50
2. Truyền tham chiếu (pass by reference) trong Java
Khi chúng ta gọi một phương thức và truyền một tham chiếu cho phương thức đó được gọi là truyền tham chiếu. Việc thay đổi giá trị của biến tham chiếu bên trong phương thức làm thay đổi giá trị gốc của nó.
Ví dụ giá trị của biến data của đối tượng op bị thay đổi sau khi gọi phương thức change():
class Operation {
int data = 50;
void change(Operation op) {
op.data = op.data + 100;// changes will be in the instance variable
}
public static void main(String args[]) {
Operation op = new Operation();
System.out.println("before change " + op.data);
op.change(op); // passing object
System.out.println("after change " + op.data);
}
}
Kết quả:
before change: 50 after change: 150
Related posts:
Java Program to Find the Vertex Connectivity of a Graph
Hướng dẫn Java Design Pattern – MVC
Java Program to Find a Good Feedback Vertex Set
New in Spring Security OAuth2 – Verify Claims
Binary Numbers in Java
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
A Guide to LinkedHashMap in Java
Introduction to Java Serialization
Check if a String is a Palindrome in Java
Java Program to Implement Affine Cipher
A Guide to ConcurrentMap
Java Program to Compute Determinant of a Matrix
Tiêu chuẩn coding trong Java (Coding Standards)
Spring Data Reactive Repositories with MongoDB
Spring WebClient vs. RestTemplate
Inject Parameters into JUnit Jupiter Unit Tests
Quick Guide to Spring Bean Scopes
Spring Cloud AWS – S3
Java Program to Implement Pollard Rho Algorithm
Java Program to Check Cycle in a Graph using Graph traversal
Java Program to Use rand and srand Functions
Java Program to Optimize Wire Length in Electrical Circuit
String Initialization in Java
Spring Boot - Tracing Micro Service Logs
Hướng dẫn Java Design Pattern – Adapter
Extract links from an HTML page
Exploring the Spring Boot TestRestTemplate
Guide to Escaping Characters in Java RegExps
Java Program to Implement Min Heap
Convert Time to Milliseconds in Java
Cài đặt và sử dụng Swagger UI
Java Program to Implement Maximum Length Chain of Pairs