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:
So sánh HashMap và Hashtable trong Java
Java Program to Show the Duality Transformation of Line and Point
Introduction to Liquibase Rollback
LIKE Queries in Spring JPA Repositories
Using JWT with Spring Security OAuth (legacy stack)
REST Pagination in Spring
New Features in Java 9
Spring WebClient and OAuth2 Support
Java – Write an InputStream to a File
Java Program to Implement Hash Tables chaining with Singly Linked Lists
Java Program to Compute Discrete Fourier Transform Using Naive Approach
Introduction to Spring Cloud Stream
Java Program to Implement Expression Tree
Configuring a DataSource Programmatically in Spring Boot
Shuffling Collections In Java
New in Spring Security OAuth2 – Verify Claims
Transactions with Spring and JPA
Anonymous Classes in Java
The Dining Philosophers Problem in Java
Java Program to Implement Floyd Cycle Algorithm
Introduction to Spring Cloud CLI
Jackson Exceptions – Problems and Solutions
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path
Java – Random Long, Float, Integer and Double
Java Program to implement Array Deque
Java Program to Represent Graph Using Linked List
Spring Web Annotations
Java – Reader to InputStream
Sử dụng CountDownLatch trong Java
Java Program to Implement Queue using Two Stacks
Hướng dẫn Java Design Pattern – Iterator
Guide to WeakHashMap in Java