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:
Getting Started with Stream Processing with Spring Cloud Data Flow
Java Program to Check whether Directed Graph is Connected using DFS
Thực thi nhiều tác vụ cùng lúc như thế nào trong Java?
Java Program to Compute the Volume of a Tetrahedron Using Determinants
Giới thiệu Swagger – Công cụ document cho RESTfull APIs
Request Method Not Supported (405) in Spring
A Guide to the Java LinkedList
Spring RestTemplate Error Handling
Java Program to Find Nearest Neighbor for Dynamic Data Set
Java Program to Implement HashTable API
Vòng lặp for, while, do-while trong Java
Java Program to Implement Booth Algorithm
Autoboxing và Unboxing trong Java
Working with Kotlin and JPA
Easy Ways to Write a Java InputStream to an OutputStream
Spring Security – Reset Your Password
Java Program to Implement Knapsack Algorithm
Jackson Unmarshalling JSON with Unknown Properties
Uploading MultipartFile with Spring RestTemplate
Xây dựng ứng dụng Client-Server với Socket trong Java
@Order in Spring
Introduction to Eclipse Collections
Java Byte Array to InputStream
Java Program to Perform Quick Sort on Large Number of Elements
Java Program to implement Bit Matrix
Hướng dẫn Java Design Pattern – Dependency Injection
Java Program to Implement PriorityQueue API
Java InputStream to String
New Features in Java 13
Java 8 Stream API Analogies in Kotlin
Java Program to Generate N Number of Passwords of Length M Each
Changing Annotation Parameters At Runtime