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:
Encode/Decode to/from Base64
Spring Boot - Batch Service
Multi Dimensional ArrayList in Java
Java – Write a Reader to File
Java Program to Perform Insertion in a BST
Custom Error Pages with Spring MVC
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Java Program to Perform LU Decomposition of any Matrix
Java Program to Implement PriorityBlockingQueue API
Overview of Spring Boot Dev Tools
Java Program to Implement Graph Coloring Algorithm
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Java Program to Implement WeakHashMap API
Guide to Selenium with JUnit / TestNG
HashSet trong java
Java Program to implement Bit Matrix
Posting with HttpClient
Java Program to Implement Selection Sort
JUnit5 Programmatic Extension Registration with @RegisterExtension
Default Password Encoder in Spring Security 5
Giới thiệu Java Service Provider Interface (SPI) – Tạo các ứng dụng Java dễ mở rộng
Java Program to Implement Hash Tables with Linear Probing
Java Program to Check Cycle in a Graph using Topological Sort
How to Delay Code Execution in Java
Giới thiệu về Stream API trong Java 8
Toán tử instanceof trong java
Spring Boot - Tracing Micro Service Logs
Java Program to Implement Cartesian Tree
Introduction to the Functional Web Framework in Spring 5
Mix plain text and HTML content in a mail
Serialize Only Fields that meet a Custom Criteria with Jackson
Using JWT with Spring Security OAuth (legacy stack)