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:
Hướng dẫn Java Design Pattern – Bridge
Java Program to Implement Borwein Algorithm
Java Program to Check if a Directed Graph is a Tree or Not Using DFS
Serve Static Resources with Spring
Implementing a Runnable vs Extending a Thread
Sử dụng CountDownLatch trong Java
Java Program to Implement Aho-Corasick Algorithm for String Matching
A Guide to Java 9 Modularity
Spring Boot Security Auto-Configuration
Map Interface trong java
Getting Started with Custom Deserialization in Jackson
The DAO with Spring and Hibernate
Java Program to Show the Duality Transformation of Line and Point
Xây dựng ứng dụng Client-Server với Socket trong Java
Spring Boot - Rest Template
Debug a HttpURLConnection problem
Java Program to Check the Connectivity of Graph Using BFS
The Order of Tests in JUnit
Java Program to Print the Kind of Rotation the AVL Tree is Undergoing
Java Program to Construct an Expression Tree for an Infix Expression
Java Program to Implement Sorted Vector
Adding Parameters to HttpClient Requests
Encode/Decode to/from Base64
Java Program to Describe the Representation of Graph using Incidence Matrix
Chuyển đổi giữa các kiểu dữ liệu trong Java
Spring Cloud – Adding Angular
Java Program to Implement Queue
Spring – Injecting Collections
Send email with authentication
How to Replace Many if Statements in Java
Java Program to Find Transitive Closure of a Graph
Spring Boot - Sending Email