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:
Lớp Collectors trong Java 8
Java Program to Delete a Particular Node in a Tree Without Using Recursion
Java Program to Implement Kosaraju Algorithm
Wrapper Classes in Java
Jackson Date
Hướng dẫn Java Design Pattern – Observer
Spring Security OAuth Login with WebFlux
Compare Two JSON Objects with Jackson
Java Program to Implement Find all Forward Edges in a Graph
Một số tính năng mới về xử lý ngoại lệ trong Java 7
Testing an OAuth Secured API with Spring MVC
Java Program to Implement Hash Tables Chaining with Binary Trees
Derived Query Methods in Spring Data JPA Repositories
Stack Memory and Heap Space in Java
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Guide to java.util.Formatter
Count Occurrences of a Char in a String
Java Stream Filter with Lambda Expression
Spring @RequestParam Annotation
Posting with HttpClient
Java Program to Find Nearest Neighbor Using Linear Search
Shuffling Collections In Java
Connect through a Proxy
Từ khóa this và super trong Java
StringBuilder vs StringBuffer in Java
Java – Write an InputStream to a File
Java Program to Implement ScapeGoat Tree
Spring Boot - Internationalization
Spring Boot - Apache Kafka
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Java Program to Implement CopyOnWriteArrayList API
Java Program to Implement Gale Shapley Algorithm