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 Data MongoDB – Indexes, Annotations and Converters
Cài đặt và sử dụng Swagger UI
Spring NoSuchBeanDefinitionException
Java 8 – Powerful Comparison with Lambdas
Use Liquibase to Safely Evolve Your Database Schema
LinkedHashSet trong java
Java Program to Compute the Volume of a Tetrahedron Using Determinants
Serverless Functions with Spring Cloud Function
Service Registration with Eureka
Java – Get Random Item/Element From a List
Spring Boot - Scheduling
Java Program to Implement Coppersmith Freivald’s Algorithm
Difference Between Wait and Sleep in Java
DistinctBy in the Java Stream API
Java Program to Implement Brent Cycle Algorithm
Transactions with Spring and JPA
A Guide to TreeMap in Java
Spring Boot - Tomcat Port Number
Guide to Spring Cloud Kubernetes
Guide to UUID in Java
Debug a JavaMail Program
Java Program to Implement ConcurrentLinkedQueue API
Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...
Registration – Activate a New Account by Email
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Java Program to Find the Longest Subsequence Common to All Sequences in a Set of Sequences
Quick Guide to Spring Bean Scopes
Count Occurrences of a Char in a String
Configuring a DataSource Programmatically in Spring Boot
Mix plain text and HTML content in a mail
Transaction Propagation and Isolation in Spring @Transactional
Giới thiệu SOAP UI và thực hiện test Web Service