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:
HandlerAdapters in Spring MVC
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
Spring MVC and the @ModelAttribute Annotation
Assert an Exception is Thrown in JUnit 4 and 5
Spring @RequestMapping New Shortcut Annotations
Hướng dẫn sử dụng luồng vào ra ký tự trong Java
Java Program to Implement Find all Back Edges in a Graph
Java Program to Implement Rope
Hướng dẫn Java Design Pattern – Memento
How to Iterate Over a Stream With Indices
Send email with SMTPS (eg. Google GMail)
Converting Iterator to List
Creating a Generic Array in Java
Configuring a DataSource Programmatically in Spring Boot
Spring MVC Content Negotiation
Spring Boot - Sending Email
Spring Webflux with Kotlin
Ways to Iterate Over a List in Java
Java Program to Generate Random Numbers Using Multiply with Carry Method
Spring REST with a Zuul Proxy
Serve Static Resources with Spring
The Java 8 Stream API Tutorial
@Order in Spring
Java Program to Implement ArrayDeque API
Exploring the Spring 5 WebFlux URL Matching
A Guide to Spring Cloud Netflix – Hystrix
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Java Program to Implement Queue using Linked List
Java Program to Represent Graph Using Adjacency List
Guide to Java 8’s Collectors
ExecutorService – Waiting for Threads to Finish
A Guide to Apache Commons Collections CollectionUtils