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 Check whether Graph is a Bipartite using BFS
Introduction to Eclipse Collections
Từ khóa static và final trong java
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
A Guide To UDP In Java
Hướng dẫn sử dụng lớp Console trong java
Working with Network Interfaces in Java
Changing Annotation Parameters At Runtime
Java Program to Implement PriorityQueue API
Java Program to Implement TreeSet API
A Guide to LinkedHashMap in Java
OAuth2 Remember Me with Refresh Token
Java Program to Implement Regular Falsi Algorithm
Java Program to Find kth Largest Element in a Sequence
Cơ chế Upcasting và Downcasting trong java
Spring 5 and Servlet 4 – The PushBuilder
Predicate trong Java 8
Custom Thread Pools In Java 8 Parallel Streams
Introduction to Spring Method Security
Connect through a Proxy
Java Program to Implement CountMinSketch
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
Derived Query Methods in Spring Data JPA Repositories
Guide to Selenium with JUnit / TestNG
Java Program to Permute All Letters of an Input String
Java Program to Describe the Representation of Graph using Adjacency List
Java Program to implement Associate Array
Reversing a Linked List in Java
Java Program to Create a Random Linear Extension for a DAG
Java Program to Find Transitive Closure of a Graph
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Convert Character Array to String in Java