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 to Implement Merge Sort Algorithm on Linked List
Java String Conversions
Spring Cloud AWS – EC2
Java Program to Implement Sorted List
Java Program to Check Whether a Directed Graph Contains a Eulerian Path
Introduction to Spring Cloud OpenFeign
A Guide to the finalize Method in Java
Vòng lặp for, while, do-while trong Java
A Custom Media Type for a Spring REST API
Lập trình đa luồng với Callable và Future trong Java
Convert Character Array to String in Java
Spring Boot - Runners
Java Program to Find the Edge Connectivity of a Graph
Java Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon
Cơ chế Upcasting và Downcasting trong java
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu
Hướng dẫn sử dụng luồng vào ra ký tự trong Java
Getting a File’s Mime Type in Java
Prevent Brute Force Authentication Attempts with Spring Security
Java Program to Implement Weight Balanced Tree
Generate Spring Boot REST Client with Swagger
A Guide to Java HashMap
Java Program to Implement Expression Tree
wait() and notify() Methods in Java
Spring Boot - Thymeleaf
Guide to the ConcurrentSkipListMap
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Guide to Character Encoding
The DAO with Spring and Hibernate
Using the Map.Entry Java Class
Chương trình Java đầu tiên
Java – Reader to String