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:
How to Get the Last Element of a Stream in Java?
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Using a Custom Spring MVC’s Handler Interceptor to Manage Sessions
Getting Started with GraphQL and Spring Boot
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
How to Store Duplicate Keys in a Map in Java?
Java Program to Perform LU Decomposition of any Matrix
Java Program to Implement Self organizing List
Guide to Java 8 groupingBy Collector
4 tính chất của lập trình hướng đối tượng trong Java
Custom Exception trong Java
Quick Intro to Spring Cloud Configuration
The Registration Process With Spring Security
Java Program to Implement Word Wrap Problem
Java Program to Implement LinkedTransferQueue API
Java Program to Implement Hash Tables
What is Thread-Safety and How to Achieve it?
Serve Static Resources with Spring
A Guide to the ViewResolver in Spring MVC
Exception Handling in Java
Java Program to Implement Graph Coloring Algorithm
Logging in Spring Boot
A Guide to the Java ExecutorService
Transaction Propagation and Isolation in Spring @Transactional
Custom Thread Pools In Java 8 Parallel Streams
Phân biệt JVM, JRE, JDK
Spring REST API + OAuth2 + Angular
Java Program to Evaluate an Expression using Stacks
Java Perform to a 2D FFT Inplace Given a Complex 2D Array
Java Program to Implement Cubic convergence 1/pi Algorithm
How to Break from Java Stream forEach