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 Change Context Path
Spring Data Java 8 Support
Converting Between a List and a Set in Java
Giới thiệu HATEOAS
The “final” Keyword in Java
Java Program to Find MST (Minimum Spanning Tree) using Kruskal’s Algorithm
Spring Data Reactive Repositories with MongoDB
Java Scanner hasNext() vs. hasNextLine()
Implementing a Runnable vs Extending a Thread
Hướng dẫn Java Design Pattern – Dependency Injection
JPA/Hibernate Persistence Context
How to Get All Spring-Managed Beans?
Java 8 Stream findFirst() vs. findAny()
Debugging Reactive Streams in Java
Jackson – JsonMappingException (No serializer found for class)
Java Program to Find Number of Articulation points in a Graph
Java NIO2 Path API
More Jackson Annotations
How to Convert List to Map in Java
Java Program to Implement Hash Tree
Format ZonedDateTime to String
Fixing 401s with CORS Preflights and Spring Security
Function trong Java 8
Registration with Spring Security – Password Encoding
LinkedHashSet trong java
Spring Security with Maven
The Dining Philosophers Problem in Java
Overview of the java.util.concurrent
The DAO with JPA and Spring
Java Program to Implement Hash Tables chaining with Singly Linked Lists
Difference Between Wait and Sleep in Java
Lấy ngày giờ hiện tại trong Java