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:
Spring Boot - Cloud Configuration Server
Kết hợp Java Reflection và Java Annotations
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
Java Program to Implement IdentityHashMap API
Removing all Nulls from a List in Java
Java Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph
Build a REST API with Spring and Java Config
Java Program to Implement Sorted Singly Linked List
Java List UnsupportedOperationException
Intro to Spring Boot Starters
Spring Boot - Enabling Swagger2
Prevent Brute Force Authentication Attempts with Spring Security
Java Program to Find the Peak Element of an Array O(n) time (Naive Method)
Spring Boot - Rest Template
Java Program to Implement Hash Trie
Mapping a Dynamic JSON Object with Jackson
A Guide to the Java LinkedList
Disable Spring Data Auto Configuration
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Java Program to Implement Interval Tree
A Guide to Spring Boot Admin
Java Program to Perform the Shaker Sort
Java Program to Implement Adjacency List
Spring Boot with Multiple SQL Import Files
Hướng dẫn Java Design Pattern – Adapter
Spring RestTemplate Request/Response Logging
Guide to the Java Queue Interface
Các nguyên lý thiết kế hướng đối tượng – SOLID
Spring Cloud AWS – EC2
Spring WebClient Requests with Parameters
Base64 encoding và decoding trong Java 8
Immutable Map Implementations in Java