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 Implement Gauss Seidel Method
Get and Post Lists of Objects with RestTemplate
Java Convenience Factory Methods for Collections
Introduction to Spring Cloud Stream
Java Program to Implement Knapsack Algorithm
Apache Camel with Spring Boot
A Guide to Concurrent Queues in Java
Convert String to Byte Array and Reverse in Java
Giới thiệu về Stream API trong Java 8
Java Program to Implement WeakHashMap API
Java Program to Find the Minimum value of Binary Search Tree
The Spring @Controller and @RestController Annotations
Apache Commons Collections MapUtils
Guide to the Fork/Join Framework in Java
Java Program to Implement Binary Heap
Stack Memory and Heap Space in Java
Java Program to Check if a Given Binary Tree is an AVL Tree or Not
Hamcrest Collections Cookbook
HTTP Authentification and CGI/Servlet
Properties with Spring and Spring Boot
Spring Cloud Bus
Spring WebFlux Filters
Java Program to Implement Depth-limited Search
Java InputStream to String
Guide to Guava Table
Generating Random Numbers in a Range in Java
Java Program to Perform Uniform Binary Search
Spring Cloud AWS – S3
Java Program to Implement Fenwick Tree
Jackson JSON Views
Xử lý ngoại lệ trong Java (Exception Handling)
How to Change the Default Port in Spring Boot