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 D-ary-Heap
How to Get a Name of a Method Being Executed?
Spring Boot - Code Structure
Get the workstation name or IP
Spring REST API + OAuth2 + Angular
Quick Guide to Spring Bean Scopes
How to Read a Large File Efficiently with Java
Flattening Nested Collections in Java
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Phân biệt JVM, JRE, JDK
Guide to the Fork/Join Framework in Java
Java Program to Implement Stack
Sort a HashMap in Java
String Processing with Apache Commons Lang 3
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)
Returning Custom Status Codes from Spring Controllers
Java Program to Solve the Fractional Knapsack Problem
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Java Program to Implement Heap
Deploy a Spring Boot App to Azure
Running Spring Boot Applications With Minikube
Java Program to Implement Affine Cipher
Guide to Escaping Characters in Java RegExps
Java Program to Construct a Random Graph by the Method of Random Edge Selection
Template Engines for Spring
Count Occurrences of a Char in a String
Guide to java.util.concurrent.Locks
Collect a Java Stream to an Immutable Collection
Hashing a Password in Java
Java Switch Statement
Java Program to Implement Efficient O(log n) Fibonacci generator
Apache Commons Collections MapUtils