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 Check Whether a Directed Graph Contains a Eulerian Path
Java 8 – Powerful Comparison with Lambdas
Java Program to Implement Max-Flow Min-Cut Theorem
Spring REST API + OAuth2 + Angular (using the Spring Security OAuth legacy stack)
Java Program to Implement Word Wrap Problem
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Java Program to Find a Good Feedback Vertex Set
Receive email by java client
Class Loaders in Java
Biểu thức Lambda trong Java 8 – Lambda Expressions
Convert Hex to ASCII in Java
Java Program to Implement Skip List
XML-Based Injection in Spring
Java Program to Implement Borwein Algorithm
Apache Commons Collections Bag
Spring Boot - Sending Email
Java Program to Implement HashTable API
Lớp lồng nhau trong java (Java inner class)
Introduction to Thread Pools in Java
Java Program to Check Whether Graph is DAG
Java Program to Implement Sorted Singly Linked List
Introduction to the Java NIO2 File API
Guide to Character Encoding
OAuth2.0 and Dynamic Client Registration
Java Program to Implement Iterative Deepening
Object Type Casting in Java
Spring Cloud – Tracing Services with Zipkin
Retrieve User Information in Spring Security
Java – Write to File
Java Program to Implement Horner Algorithm
Introduction to Liquibase Rollback