Java is pass-by-value.
Pass by value: make a copy in memory of the actual parameter"s value that is passed in.
Pass by reference: pass a copy of the address of the actual parameter.
This code will not swap anything:
void swap(Type a1, Type a2) { Type temp = a1; a1 = a2; a2 = temp; }
For this code, since the original and copied reference refer the same object, the member value gets changed:
class Apple { public String color = "red"; } public class main { public static void main(String[] args) { Apple a1 = new Apple(); System.out.println(a1.color); //print "red" changeColor(a1); System.out.println(a1.color); //print "green" } public static void changeColor(Apple apple) { apple.color = "green"; } }
Java does manipulate objects by reference, and all object variables are references. However, Java doesn"t pass method arguments by reference; it passes them by value.
Some more examplespublic class Main { public static void main(String[] args) { Student s = new Student("John"); changeName(s); System.out.printf(s); // will print "John" modifyName(s); System.out.printf(s); // will print "Dave" } public static void changeName(Student a) { Student b = new Student("Mary"); a = b; } public static void modifyName(Student c) { c.setAttribute("Dave"); } }
public static void changeContent(int[] arr) { // If we change the content of arr. arr[0] = 10; // Will change the content of array in main() } public static void changeRef(int[] arr) { arr = new int[2]; // If we change the reference arr[0] = 15; // Will not change the array in main() } public static void main(String[] args) { int [] arr = new int[2]; arr[0] = 4; arr[1] = 5; changeContent(arr); System.out.println(arr[0]); // Will print 10.. changeRef(arr); System.out.println(arr[0]); // Will still print 10.. }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/65062.html
What is Java? Java is a high-level platform-independent object oriented programming language. List some features of Java? Object Oriented, Platform Independent, Multi-threaded, Interpreted, Robust, pa...
摘要:原文地址這里列出了十個常見而又刁鉆的開發(fā)人員面試題及答案,這些題目是我從上找來的。如果你是初中級開發(fā)人員,而且近期準(zhǔn)備面試的話,這些題目可能對你有些幫助。成員即沒有訪問修飾符的成員可以在當(dāng)前包下的所有類中訪問到。 原文地址:https://dzone.com/articles/10... 這里列出了十個常見而又刁鉆的 Java 開發(fā)人員面試題及答案,這些題目是我從 StackOverf...
摘要:我會解釋里面神秘的引用,一旦你理解了引用,你就會明白通過引用來了解的綁定是多么輕松,你也會發(fā)現(xiàn)讀的規(guī)范容易得多了。二理論把引用定義成??纯催\算符的說法這也就是為什么我們對一個無法解析的引用使用操作符的時候并不會報錯。 Know thy reference (原文:know thy reference - kangax) 一、前言 翻譯好不是件容易的事兒,我盡量講得通順,一些術(shù)語會保留原...
摘要:根據(jù)調(diào)查,自年一來,是最流行的編程語言。在一個函數(shù)體中聲明的變量和函數(shù),周圍的作用域內(nèi)無法訪問。也就是說被大括號包圍起來的區(qū)域聲明的變量外部將不可訪問。一個常見的誤解是使用聲明的變量,其值不可更改。 譯者按: 總結(jié)了大量JavaScript基本知識點,很有用! 原文: The Definitive JavaScript Handbook for your next developer ...
閱讀 3158·2021-11-22 13:54
閱讀 3450·2021-11-15 11:37
閱讀 3612·2021-10-14 09:43
閱讀 3508·2021-09-09 11:52
閱讀 3612·2019-08-30 15:53
閱讀 2474·2019-08-30 13:50
閱讀 2065·2019-08-30 11:07
閱讀 897·2019-08-29 16:32