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:
Giới thiệu thư viện Apache Commons Chain
Java InputStream to String
Java Program to Represent Graph Using Adjacency List
Java Program to Implement Doubly Linked List
Transaction Propagation and Isolation in Spring @Transactional
Spring MVC Custom Validation
Java Program to Implement TreeSet API
Hướng dẫn sử dụng luồng vào ra ký tự trong Java
Java Program to Implement Self Balancing Binary Search Tree
Concatenating Strings In Java
Spring Boot - Flyway Database
Guide to UUID in Java
Java Program to Implement Sparse Matrix
A Quick Guide to Spring MVC Matrix Variables
Introduction to Eclipse Collections
Java Program to Implement Control Table
Java Program to Check for balanced parenthesis by using Stacks
Functional Interfaces in Java 8
Introduction to Spring Data MongoDB
Derived Query Methods in Spring Data JPA Repositories
Spring Boot - Cloud Configuration Client
Spring Boot - Quick Start
Hướng dẫn Java Design Pattern – Visitor
The StackOverflowError in Java
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Java Program to Construct an Expression Tree for an Postfix Expression
Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...
REST Pagination in Spring
Java Program to Implement Stack API
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Java Program to Find Maximum Element in an Array using Binary Search