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:
Adding Parameters to HttpClient Requests
Java Program to Perform String Matching Using String Library
How to Use if/else Logic in Java 8 Streams
Spring Data MongoDB Transactions
Java Program to Implement Adjacency List
Comparing Two HashMaps in Java
Java Program to Implement LinkedBlockingDeque API
Jackson – Unmarshall to Collection/Array
Count Occurrences of a Char in a String
Injecting Prototype Beans into a Singleton Instance in Spring
Service Registration with Eureka
Semaphore trong Java
Java Program to Implement Floyd-Warshall Algorithm
Java Program to Implement Quick Hull Algorithm to Find Convex Hull
Spring Security – Reset Your Password
Working With Maps Using Streams
Java Program to Optimize Wire Length in Electrical Circuit
Java – Write an InputStream to a File
Luồng Daemon (Daemon Thread) trong Java
Java Program to Implement Min Heap
How To Serialize and Deserialize Enums with Jackson
LIKE Queries in Spring JPA Repositories
HttpClient 4 Cookbook
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Java Program to Implement Gale Shapley Algorithm
Java Program to Find the Vertex Connectivity of a Graph
Java Program to Perform Preorder Recursive Traversal of a Given Binary Tree
Từ khóa throw và throws trong Java
Java Program to Implement Shoelace Algorithm
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
Java Program to Implement Disjoint Set Data Structure
A Guide to @RepeatedTest in Junit 5