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 – Create a File
Sorting in Java
Template Engines for Spring
Upload and Display Excel Files with Spring MVC
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Login For a Spring Web App – Error Handling and Localization
Converting between an Array and a List in Java
How to Define a Spring Boot Filter?
Java Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon
Spring Security 5 for Reactive Applications
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
How to Add a Single Element to a Stream
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)
Java String Conversions
Converting Between a List and a Set in Java
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Java Program to Solve Tower of Hanoi Problem using Stacks
Java Program to Implement Naor-Reingold Pseudo Random Function
Java Program to Implement ConcurrentSkipListMap API
Java Program to Use Boruvka’s Algorithm to Find the Minimum Spanning Tree
New Features in Java 9
Java Program to Implement JobStateReasons API
Implementing a Binary Tree in Java
A Guide to Iterator in Java
Java Program to Implement Disjoint Sets
Apache Commons Collections SetUtils
Lớp Collections trong Java (Collections Utility Class)
Query Entities by Dates and Times with Spring Data JPA
Java Program to implement Associate Array
A Guide to EnumMap
Lập trình hướng đối tượng (OOPs) trong java
Use Liquibase to Safely Evolve Your Database Schema