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:
Stack Memory and Heap Space in Java
Java Program to find the peak element of an array using Binary Search approach
How to Change the Default Port in Spring Boot
Remove the First Element from a List
Updating your Password
Tips for dealing with HTTP-related problems
How To Serialize and Deserialize Enums with Jackson
Java Program to Implement Heap Sort Using Library Functions
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Lớp Collectors trong Java 8
Java Program to Implement Bloom Filter
Java Program to Implement Rope
Error Handling for REST with Spring
Java Program to Create the Prufer Code for a Tree
Java Program to Decode a Message Encoded Using Playfair Cipher
Array to String Conversions
Java – Reader to InputStream
Java CyclicBarrier vs CountDownLatch
A Guide to @RepeatedTest in Junit 5
Java – Write an InputStream to a File
Java Program to Find Number of Articulation points in a Graph
Java 8 – Powerful Comparison with Lambdas
Tránh lỗi NullPointerException trong Java như thế nào?
Check If a File or Directory Exists in Java
Spring Security OAuth Login with WebFlux
Returning Custom Status Codes from Spring Controllers
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
REST Pagination in Spring
Create a Custom Exception in Java
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Java Program to Implement Gift Wrapping Algorithm in Two Dimensions
Java Program to Implement Variable length array