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:
How to Round a Number to N Decimal Places in Java
Java Program to Implement Caesar Cypher
Check if a String is a Palindrome in Java
What is a POJO Class?
Spring Boot - Thymeleaf
The Order of Tests in JUnit
Fixing 401s with CORS Preflights and Spring Security
How to use the Spring FactoryBean?
Java Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
Apache Camel with Spring Boot
Hướng dẫn Java Design Pattern – Adapter
Java Program to Find Median of Elements where Elements are Stored in 2 Different Arrays
Send an email using the SMTP protocol
Vector trong Java
Jackson – Marshall String to JsonNode
Jackson – Bidirectional Relationships
Autoboxing và Unboxing trong Java
Lớp Arrarys trong Java (Arrays Utility Class)
Get the workstation name or IP
Batch Processing with Spring Cloud Data Flow
Java Program to Implement ArrayList API
Java Program to Implement Gale Shapley Algorithm
Java Program to Implement RoleList API
A Guide to Java SynchronousQueue
Removing all Nulls from a List in Java
Spring RestTemplate Error Handling
Java Program to Implement Fermat Primality Test Algorithm
How to Find an Element in a List with Java
Finding the Differences Between Two Lists in Java
Setting a Request Timeout for a Spring REST API
Java Program to Implement Gaussian Elimination Algorithm
Hướng dẫn Java Design Pattern – Memento