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 for Douglas-Peucker Algorithm Implementation
Getting a File’s Mime Type in Java
MyBatis with Spring
Java Program to Implement RoleList API
Một số nguyên tắc, định luật trong lập trình
Lớp HashMap trong Java
Test a REST API with Java
Java Program to Implement AVL Tree
Java Program to Check if a Directed Graph is a Tree or Not Using DFS
Introduction to the Functional Web Framework in Spring 5
Java String Conversions
HttpClient 4 – Send Custom Cookie
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Java Program to Implement Hash Tables chaining with Singly Linked Lists
Spring Boot - Build Systems
Java Program to Implement Splay Tree
Java Program to Find the Mode in a Data Set
A Guide to Queries in Spring Data MongoDB
Java 14 Record Keyword
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Spring Boot Integration Testing with Embedded MongoDB
Java Program to Implement TreeMap API
Java Program to Perform Polygon Containment Test
Java Program to Implement Expression Tree
Java InputStream to Byte Array and ByteBuffer
Transactions with Spring and JPA
Java Program to Implement Karatsuba Multiplication Algorithm
Spring Cloud Bus
Spring 5 Testing with @EnabledIf Annotation
Java Program to Implement Fermat Factorization Algorithm
Java Program to Implement Threaded Binary Tree
Send email with authentication