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:
Runnable vs. Callable in Java
Biểu thức Lambda trong Java 8 – Lambda Expressions
Java Program to Implement Dijkstra’s Algorithm using Priority Queue
Spring REST API with Protocol Buffers
A Guide to System.exit()
Hướng dẫn sử dụng Printing Service trong Java
A Guide to the ViewResolver in Spring MVC
Java String Conversions
Logout in an OAuth Secured Application
Merging Two Maps with Java 8
Java Program to Implement Binary Heap
Performance Difference Between save() and saveAll() in Spring Data
Spring Data JPA Delete and Relationships
Java Program to Implement Gaussian Elimination Algorithm
Introduction to Spring Data REST
Case-Insensitive String Matching in Java
File Upload with Spring MVC
Giới thiệu Design Patterns
Giới thiệu thư viện Apache Commons Chain
Hướng dẫn sử dụng Java Generics
Transaction Propagation and Isolation in Spring @Transactional
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
The Dining Philosophers Problem in Java
Java 8 Collectors toMap
So sánh ArrayList và LinkedList trong Java
Java Program to Implement Red Black Tree
A Guide to Concurrent Queues in Java
Java Program to Check the Connectivity of Graph Using DFS
Upload and Display Excel Files with Spring MVC
Java Program to Perform Polygon Containment Test
JUnit5 @RunWith
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters