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 Search for an Element in a Binary Search Tree
Chuyển đổi giữa các kiểu dữ liệu trong Java
Java – Combine Multiple Collections
An Intro to Spring Cloud Task
Guide to Escaping Characters in Java RegExps
Get the workstation name or IP
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
New Features in Java 8
Spring Boot - Actuator
Using Spring @ResponseStatus to Set HTTP Status Code
Spring Boot - Tomcat Deployment
How to Add a Single Element to a Stream
Java Program to Perform Finite State Automaton based Search
Collection trong java
Java Program to Implement Bresenham Line Algorithm
Java Program to Implement Double Order Traversal of a Binary Tree
Converting a Stack Trace to a String in Java
Spring Security – security none, filters none, access permitAll
Java Program to Implement Brent Cycle Algorithm
Consuming RESTful Web Services
Java Program to Implement Best-First Search
Easy Ways to Write a Java InputStream to an OutputStream
Introduction to Eclipse Collections
Comparing Arrays in Java
Java Program to Implement Hash Tables chaining with Singly Linked Lists
New Features in Java 10
So sánh HashMap và Hashtable trong Java
Java Program to Check whether Graph is Biconnected
What is a POJO Class?
Java Program to Find a Good Feedback Vertex Set
Using the Not Operator in If Conditions in Java
Hướng dẫn Java Design Pattern – Interpreter