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 Compute DFT Coefficients Directly
Hướng dẫn sử dụng Java Annotation
Array to String Conversions
Java Program to Implement Quick Sort with Given Complexity Constraint
Mockito and JUnit 5 – Using ExtendWith
Java Program to Implement the Monoalphabetic Cypher
New Features in Java 11
Java Program to Implement Naor-Reingold Pseudo Random Function
Removing all Nulls from a List in Java
Giới thiệu Swagger – Công cụ document cho RESTfull APIs
Apache Commons Collections Bag
Introduction to Spliterator in Java
OAuth2 Remember Me with Refresh Token
Java Program to Check if a Matrix is Invertible
Spring Security 5 for Reactive Applications
Mix plain text and HTML content in a mail
Guide to WeakHashMap in Java
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Java Program to Implement Queue
Phương thức forEach() trong java 8
Sort a HashMap in Java
Java Program to Implement Sieve Of Eratosthenes
Ways to Iterate Over a List in Java
Java Program to Implement Direct Addressing Tables
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
File Upload with Spring MVC
The Guide to RestTemplate
Java Program to Decode a Message Encoded Using Playfair Cipher
Apache Commons Collections BidiMap
Spring Boot - Admin Client
Từ khóa throw và throws trong Java
Java Program to Implement Sorted Array