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 equals() and hashCode() Contracts
Java Program to Generate All Pairs of Subsets Whose Union Make the Set
Remove HTML tags from a file to extract only the TEXT
Comparing Strings in Java
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Luồng Daemon (Daemon Thread) trong Java
Java Program to Implement Fermat Primality Test Algorithm
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
Spring Boot - Bootstrapping
Spring REST API + OAuth2 + Angular
Returning Custom Status Codes from Spring Controllers
The Registration Process With Spring Security
Toán tử instanceof trong java
Java Program to Implement PriorityQueue API
Java Streams vs Vavr Streams
Hướng dẫn sử dụng String Format trong Java
Java Program to Implement Range Tree
Converting Java Date to OffsetDateTime
Posting with HttpClient
Spring NoSuchBeanDefinitionException
Java Program to Implement Selection Sort
Java Program to Implement ConcurrentLinkedQueue API
Adding Shutdown Hooks for JVM Applications
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
Working With Maps Using Streams
Generating Random Dates in Java
Getting Started with Custom Deserialization in Jackson
Spring REST API + OAuth2 + Angular
How to Delay Code Execution in Java
SOAP Web service: Authentication trong JAX-WS
Java Program to Check Whether a Directed Graph Contains a Eulerian Cycle
Programmatic Transaction Management in Spring