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 Hash Tables Chaining with List Heads
Service Registration with Eureka
Mảng (Array) trong Java
So sánh ArrayList và LinkedList trong Java
Java Program to Implement Kosaraju Algorithm
Deploy a Spring Boot WAR into a Tomcat Server
Checked and Unchecked Exceptions in Java
Java Program to Implement the Vigenere Cypher
Arrays.asList vs new ArrayList(Arrays.asList())
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
Overflow and Underflow in Java
Removing all Nulls from a List in Java
Java Program to Describe the Representation of Graph using Adjacency List
REST Web service: Upload và Download file với Jersey 2.x
Java Program to Implement the Program Used in grep/egrep/fgrep
Spring Webflux with Kotlin
Java Program to Implement Depth-limited Search
Limiting Query Results with JPA and Spring Data JPA
Giới thiệu luồng vào ra (I/O) trong Java
DistinctBy in the Java Stream API
Java Program to Implement Suffix Array
Request a Delivery / Read Receipt in Javamail
Spring Data JPA @Query
Java Program to Perform Insertion in a 2 Dimension K-D Tree
Spring Boot: Customize Whitelabel Error Page
Kết hợp Java Reflection và Java Annotations
Java Program to Implement Warshall Algorithm
Guide to java.util.concurrent.BlockingQueue
Java InputStream to String
Java Program to Implement Skew Heap
Merging Streams in Java
Java Program to Implement Leftist Heap