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 Implement Bresenham Line Algorithm
Spring Data – CrudRepository save() Method
Spring Boot - Thymeleaf
Spring Boot - Rest Controller Unit Test
Java – Reader to InputStream
Apache Commons Collections SetUtils
Interface trong Java 8 – Default method và Static method
Using the Map.Entry Java Class
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Spring Boot - Tomcat Deployment
Calling Stored Procedures from Spring Data JPA Repositories
Java Program to Implement the Program Used in grep/egrep/fgrep
Converting String to Stream of chars
Annotation trong Java 8
Queue và PriorityQueue trong Java
Integer Constant Pool trong Java
A Quick Guide to Using Keycloak with Spring Boot
Hướng dẫn Java Design Pattern – Abstract Factory
Get and Post Lists of Objects with RestTemplate
Java Program to Find Minimum Element in an Array using Linear Search
Tips for dealing with HTTP-related problems
Primitive Type Streams in Java 8
Spring – Injecting Collections
Java List UnsupportedOperationException
Java Program to Implement ConcurrentHashMap API
Spring Boot - Exception Handling
Using the Not Operator in If Conditions in Java
HandlerAdapters in Spring MVC
Java Program to Generate Random Hexadecimal Byte
LinkedHashSet trong Java hoạt động như thế nào?
Spring @RequestParam Annotation
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach