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 Find a Good Feedback Edge Set in a Graph
Server-Sent Events in Spring
Spring Boot - Tracing Micro Service Logs
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
Logout in an OAuth Secured Application
Send an email using the SMTP protocol
RegEx for matching Date Pattern in Java
Function trong Java 8
Java Program to Implement Merge Sort on n Numbers Without tail-recursion
Java Program to Implement the RSA Algorithm
A Quick Guide to Spring MVC Matrix Variables
HTTP Authentification and CGI/Servlet
Java Program to Implement CopyOnWriteArraySet API
A Quick Guide to Using Keycloak with Spring Boot
Java Program to Compute Discrete Fourier Transform Using Naive Approach
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Java Program to implement Sparse Vector
The DAO with Spring and Hibernate
Java Program to Create a Random Linear Extension for a DAG
Java Program to Implement LinkedList API
A Guide to WatchService in Java NIO2
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Java Program to add two large numbers using Linked List
Hashing a Password in Java
Hướng dẫn Java Design Pattern – Abstract Factory
Java Program to Check Multiplicability of Two Matrices
MyBatis with Spring
Các kiểu dữ liệu trong java
Java Program to Optimize Wire Length in Electrical Circuit
A Guide to LinkedHashMap in Java
Java Program to Implement Shell Sort
Java Program to find the number of occurrences of a given number using Binary Search approach