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:
Apache Commons Collections Bag
Java Program to Perform the Shaker Sort
Java Program to Implement Skip List
Versioning a REST API
Guide to Guava Table
TreeSet và sử dụng Comparable, Comparator trong java
Sort a HashMap in Java
Java Program to Construct an Expression Tree for an Postfix Expression
Java Program to Describe the Representation of Graph using Adjacency List
Guide to Spring 5 WebFlux
New Features in Java 11
Comparing Two HashMaps in Java
Java Program to Implement Bucket Sort
Giới thiệu Aspect Oriented Programming (AOP)
Create a Custom Exception in Java
REST Web service: Basic Authentication trong Jersey 2.x
String Operations with Java Streams
Java Program to Find the Longest Path in a DAG
Introduction to Spring Cloud Stream
Form Validation with AngularJS and Spring MVC
Hướng dẫn Java Design Pattern – Decorator
A Guide to Concurrent Queues in Java
Từ khóa static và final trong java
Hướng dẫn Java Design Pattern – DAO
Java Program to Implement Miller Rabin Primality Test Algorithm
Java Program to Solve Knapsack Problem Using Dynamic Programming
Merging Two Maps with Java 8
Java Program to Find the Edge Connectivity of a Graph
Deploy a Spring Boot App to Azure
Guide to the Synchronized Keyword in Java
Java Program to Compute Determinant of a Matrix
Spring Security Registration – Resend Verification Email