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 Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Java Program to Implement Depth-limited Search
Spring Boot - Twilio
A Comparison Between Spring and Spring Boot
Hướng dẫn Java Design Pattern – Proxy
Spring Boot - Tomcat Port Number
Concatenating Strings In Java
Hướng dẫn Java Design Pattern – Chain of Responsibility
Cachable Static Assets with Spring MVC
Spring Security 5 for Reactive Applications
Using the Not Operator in If Conditions in Java
Using JWT with Spring Security OAuth (legacy stack)
Java Program to Check whether Undirected Graph is Connected using DFS
Jackson vs Gson
Guide to Escaping Characters in Java RegExps
New Features in Java 8
Spring Boot - Sending Email
Java Program to find the maximum subarray sum O(n^2) time(naive method)
Java Program to Implement ArrayBlockingQueue API
Introduction to Java 8 Streams
Spring Boot - Admin Server
Guide to BufferedReader
Concurrent Test Execution in Spring 5
Java Program to Find the Connected Components of an UnDirected Graph
The StackOverflowError in Java
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
A Guide to TreeMap in Java
Daemon Threads in Java
Java Program to Implement Quick sort
Java Program to Solve the Fractional Knapsack Problem
Java Program to implement Priority Queue
Java Program to Implement Doubly Linked List