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:
Custom Thread Pools In Java 8 Parallel Streams
Spring Boot - Building RESTful Web Services
New Features in Java 8
Hướng dẫn sử dụng Java Generics
Java Program to Implement Horner Algorithm
Create a Custom Exception in Java
Converting Strings to Enums in Java
Spring MVC and the @ModelAttribute Annotation
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
Flattening Nested Collections in Java
Getting Started with Custom Deserialization in Jackson
String Operations with Java Streams
Removing Elements from Java Collections
Spring WebClient vs. RestTemplate
Spring REST API with Protocol Buffers
Logout in an OAuth Secured Application
The Basics of Java Security
Spring WebClient and OAuth2 Support
Error Handling for REST with Spring
Java Program to Implement an Algorithm to Find the Global min Cut in a Graph
Bootstrapping Hibernate 5 with Spring
Java Switch Statement
Tính kế thừa (Inheritance) trong java
Java Program to implement Array Deque
Spring 5 Functional Bean Registration
Jackson – JsonMappingException (No serializer found for class)
Java Collections Interview Questions
Validations for Enum Types
Java Program to Implement the String Search Algorithm for Short Text Sizes
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Java Program to Implement Nth Root Algorithm