public static void main(String[] args) {Dog aDog = new Dog("Max");Dog oldDog = aDog;
// we pass the object to foofoo(aDog);// aDog variable is still pointing to the "Max" dog when foo(...) returnsaDog.getName().equals("Max"); // trueaDog.getName().equals("Fifi"); // falseaDog == oldDog; // true}
public static void foo(Dog d) {d.getName().equals("Max"); // true// change d inside of foo() to point to a new Dog instance "Fifi"d = new Dog("Fifi");d.getName().equals("Fifi"); // true}
public static void main(String[] args) {Dog aDog = new Dog("Max");Dog oldDog = aDog;
foo(aDog);// when foo(...) returns, the name of the dog has been changed to "Fifi"aDog.getName().equals("Fifi"); // true// but it is still the same dog:aDog == oldDog; // true}
public static void foo(Dog d) {d.getName().equals("Max"); // true// this changes the name of d to be "Fifi"d.setName("Fifi");}
public class Test {public static void main(String[] args) {Integer a = new Integer(2);Integer b = new Integer(3);System.out.println("Before: a = " + a + ", b = " + b);swap(a,b);System.out.println("After: a = " + a + ", b = " + b);}
public static swap(Integer iA, Integer iB) {Integer tmp = iA;iA = iB;iB = tmp;}}
void cppMethod(int val, int &ref, Dog obj, Dog &objRef, Dog *objPtr, Dog *&objPtrRef){val = 7; // Modifies the copyref = 7; // Modifies the original variableobj.SetName("obj"); // Modifies the copy of Dog passedobjRef.SetName("objRef"); // Modifies the original Dog passedobjPtr->SetName("objPtr"); // Modifies the original Dog pointed to// by the copy of the pointer passed.objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,// leaving the original object alone.objPtrRef->SetName("objRefPtr"); // Modifies the original Dog pointed to// by the original pointer passed.objPtrRef = new Dog("newObjPtrRef"); // Modifies the original pointer passed}
int main(){int a = 0;int b = 0;Dog d0 = Dog("d0");Dog d1 = Dog("d1");Dog *d2 = new Dog("d2");Dog *d3 = new Dog("d3");cppMethod(a, b, d0, d1, d2, d3);// a is still set to 0// b is now set to 7// d0 still have name "d0"// d1 now has name "objRef"// d2 now has name "objPtr"// d3 now has name "newObjPtrRef"}
Java,
public static void javaMethod(int val, Dog objPtr){val = 7; // Modifies the copyobjPtr.SetName("objPtr") // Modifies the original Dog pointed to// by the copy of the pointer passed.objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,// leaving the original object alone.}
public static void main(){int a = 0;Dog d0 = new Dog("d0");javaMethod(a, d0);// a is still set to 0// d0 now has name "objPtr"}
public static void appendWorld(StringBuffer s1) {s1.append(" World");}
public static void main(String[] args) {StringBuffer s = new StringBuffer("Hello");appendWorld(s);System.out.println(s);}
public static void appendWorld(String s){s = s+" World";}
public static void main(String[] args) {String s = new String("Hello");appendWorld(s);System.out.println(s);}
但是,您可以像这样为String制作一个包装器,这将使其能够与Strings一起使用:
class StringWrapper {public String value;
public StringWrapper(String value) {this.value = value;}}
public static void appendWorld(StringWrapper s){s.value = s.value +" World";}
public static void main(String[] args) {StringWrapper s = new StringWrapper("Hello");appendWorld(s);System.out.println(s.value);}
1. Person person;2. person = new Person("Tom");3. changeName(person);4.5. //I didn't use Person person below as an argument to be nice6. static void changeName(Person anotherReferenceToTheSamePersonObject) {7. anotherReferenceToTheSamePersonObject.setName("Jerry");8. }
void renameToJon(Person p) {p = new Person("Jon"); // this will not work}
jack = new Person("Jack");renameToJon(jack);sysout(jack); // jack is unchanged
public class Main {
public static void main(String[] args) {Foo f = new Foo("f");changeReference(f); // It won't change the reference!modifyReference(f); // It will modify the object that the reference variable "f" refers to!}
public static void changeReference(Foo a) {Foo b = new Foo("b");a = b;}
public static void modifyReference(Foo c) {c.setAttribute("c");}
}
class Example{public static void test (Cat ref){// 3 - <ref> is a copy of the reference <a>// both currently reference GrumpySystem.out.println(ref.getName());
// 4 - now <ref> references a new <Cat> object named "Nyan"ref = new Cat("Nyan");
// 5 - this should print "Nyan"System.out.println( ref.getName() );}
public static void main (String [] args){// 1 - a is a <Cat> reference that references a Cat object in memory with name "Grumpy"Cat a = new Cat("Grumpy");
// 2 - call to function test which takes a <Cat> referencetest (a);
// 6 - function call ends, and <ref> life-time ends// "Nyan" object has no references and the Garbage// Collector will remove it from memory when invoked
// 7 - this should print "Grumpy"System.out.println(a.getName());}}
public void test() {MyClass obj = null;init(obj);//After calling init method, obj still points to null//this is because obj is passed as value and not as reference.}private void init(MyClass objVar) {objVar = new MyClass();}
package test.abc;
public class TestObject {
/*** @param args*/public static void main(String[] args) {bar();}
static void bar() {Foo f = new Foo();System.out.println("Object reference for f: " + f);f.setName("James");doStuff(f);System.out.println(f.getName());//Can change the state of an object variable in f, but can't change the object reference for f.//You still have 2 foo objects.System.out.println("Object reference for f: " + f);}
static void doStuff(Foo g) {g.setName("Boo");g = new Foo();System.out.println("Object reference for g: " + g);}}
package test.abc;
public class Foo {public String name = "";
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
public class PassByValue {public static void main(String[] args) {Test t = new Test();t.name = "initialvalue";new PassByValue().changeValue(t);System.out.println(t.name);}
public void changeValue(Test f) {f.name = "changevalue";}}
class Test {String name;}
public class PassByValue {public static void main(String[] args) {Test t = new Test();t.name = "initialvalue";new PassByValue().changeRefence(t);System.out.println(t.name);}
public void changeRefence(Test f) {f = null;}}
class Test {String name;}
The following code example illustrates this point:1 public class PassTest {23 // Methods to change the current values4 public static void changeInt(int value) {5 value = 55;6 }7 public static void changeObjectRef(MyDate ref) {8 ref = new MyDate(1, 1, 2000);9 }10 public static void changeObjectAttr(MyDate ref) {11 ref.setDay(4);12 }1314 public static void main(String args[]) {15 MyDate date;16 int val;1718 // Assign the int19 val = 11;20 // Try to change it21 changeInt(val);22 // What is the current value?23 System.out.println("Int value is: " + val);2425 // Assign the date26 date = new MyDate(22, 7, 1964);27 // Try to change it28 changeObjectRef(date);29 // What is the current value?30 System.out.println("MyDate: " + date);3132 // Now change the day attribute33 // through the object reference34 changeObjectAttr(date);35 // What is the current value?36 System.out.println("MyDate: " + date);37 }38 }
This code outputs the following:java PassTestInt value is: 11MyDate: 22-7-1964MyDate: 4-7-1964The MyDate object is not changed by the changeObjectRef method;however, the changeObjectAttr method changes the day attribute of theMyDate object.
public class Dog {
String dog ;static int x_static;int y_not_static;
public String getName(){return this.dog;}
public Dog(String dog){this.dog = dog;}
public void setName(String name){this.dog = name;}
public static void foo(Dog someDog){x_static = 1;// y_not_static = 2; // not possible !!someDog.setName("Max"); // AAAsomeDog = new Dog("Fifi"); // BBBsomeDog.setName("Rowlf"); // CCC}
public static void main(String args[]){Dog myDog = new Dog("Rover");foo(myDog);System.out.println(myDog.getName());}}
void incrementValue(int inFunction){inFunction ++;System.out.println("In function: " + inFunction);}
int original = 10;System.out.print("Original before: " + original);incrementValue(original);System.out.println("Original after: " + original);
We see in the console:> Original before: 10> In Function: 11> Original after: 10 (NO CHANGE)
public class Yo {public static void foo(int x){System.out.println(x); //out 2x = x+2;System.out.println(x); // out 4}public static void foo(int[] x){System.out.println(x[0]); //1x[0] = x[0]+2;System.out.println(x[0]); //3}public static void main(String[] args) {int t = 2;foo(t);System.out.println(t); // out 2 (t did not change in foo)
int[] tab = new int[]{1};foo(tab);System.out.println(tab[0]); // out 3 (tab[0] did change in foo)}}
public class PassByValueString {public static void main(String[] args) {new PassByValueString().caller();}
public void caller() {String value = "Nikhil";boolean valueflag = false;String output = method(value, valueflag);/** 'output' is insignificant in this example. we are more interested in* 'value' and 'valueflag'*/System.out.println("output : " + output);System.out.println("value : " + value);System.out.println("valueflag : " + valueflag);
}
public String method(String value, boolean valueflag) {value = "Anand";valueflag = true;return "output";}}
结果
output : outputvalue : Nikhilvalueflag : false
示例2:
/****通过值**/
public class PassByValueNewString {public static void main(String[] args) {new PassByValueNewString().caller();}
public void caller() {String value = new String("Nikhil");boolean valueflag = false;String output = method(value, valueflag);/** 'output' is insignificant in this example. we are more interested in* 'value' and 'valueflag'*/System.out.println("output : " + output);System.out.println("value : " + value);System.out.println("valueflag : " + valueflag);
}
public String method(String value, boolean valueflag) {value = "Anand";valueflag = true;return "output";}}
注意:我没有粘贴private class Student的代码。Student的类定义与示例3相同。
*/
public class PassByValueObjectCase2 {
public static void main(String[] args) {new PassByValueObjectCase2().caller();}
public void caller() {// student has the actual reference to a Student object created// can we change this actual reference outside the local scope? Let's seeStudent student = new Student(10, "Nikhil");String output = method(student);/** 'output' is insignificant in this example. we are more interested in* 'student'*/System.out.println("output : " + output);System.out.println("student : " + student); // Will it print Nikhil or Anand?}
public String method(Student student) {student = new Student(20, "Anand");return "output";}
}
public static void increment(int x) { x++; }
int a = 3;increment(a);
x将复制a的值并递增x,a保持不变
2)尝试更改对象的原始字段
public static void increment(Person p) { p.age++; }
Person pers = new Person(20); // age = 20increment(pers);
p将复制per的引用值并增加age字段,变量引用同一个对象,因此age会改变
3)尝试更改引用变量的引用值
public static void swap(Person p1, Person p2) {Person temp = p1;p1 = p2;p2 = temp;}
Person pers1 = new Person(10);Person pers2 = new Person(20);swap(pers1, pers2);
public class Doggie {
public static void main(String...args) {System.out.println("At the owner's home:");Dog d = new Dog(12);d.wag();goodVet(d);System.out.println("With the owner again:)");d.wag();badVet(d);System.out.println("With the owner again(:");d.wag();}
public static void goodVet (Dog dog) {System.out.println("At the good vet:");dog.wag();dog = new Dog(12); // create a clonedog.cutTail(6); // cut the clone's taildog.wag();}
public static void badVet (Dog dog) {System.out.println("At the bad vet:");dog.wag();dog.cutTail(2); // cut the original dog's taildog.wag();}}
class Dog {
int tailLength;
public Dog(int originalLength) {this.tailLength = originalLength;}
public void cutTail (int newLength) {this.tailLength = newLength;}
public void wag() {System.out.println("Wagging my " +tailLength +" inch tail");}}
Output:At the owner's home:Wagging my 12 inch tailAt the good vet:Wagging my 12 inch tailWagging my 6 inch tailWith the owner again:)Wagging my 12 inch tailAt the bad vet:Wagging my 12 inch tailWagging my 2 inch tailWith the owner again(:Wagging my 2 inch tail
public class Balloon {
private String color;
public Balloon(){}
public Balloon(String c){this.color=c;}
public String getColor() {return color;}
public void setColor(String color) {this.color = color;}}
我们有一个简单的程序,用一个泛型方法来交换两个对象,类如下所示。
public class Test {
public static void main(String[] args) {
Balloon red = new Balloon("Red"); //memory reference 50Balloon blue = new Balloon("Blue"); //memory reference 100
swap(red, blue);System.out.println("red color="+red.getColor());System.out.println("blue color="+blue.getColor());
foo(blue);System.out.println("blue color="+blue.getColor());
}
private static void foo(Balloon balloon) { //baloon=100balloon.setColor("Red"); //baloon=100balloon = new Balloon("Green"); //baloon=200balloon.setColor("Blue"); //baloon = 200}
//Generic swap methodpublic static void swap(Object o1, Object o2){Object temp = o1;o1=o2;o2=temp;}}
public class AssignmentEvaluation{static public class MyInteger{public int value = 0;}
static public void main(String[] args){System.out.println("Assignment operator evaluation using two MyInteger objects named height and width\n");
MyInteger height = new MyInteger();MyInteger width = new MyInteger();
System.out.println("[1] Assign distinct integers to height and width values");
height.value = 9;width.value = 1;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", we are different things! \n");
System.out.println("[2] Assign to height's value the width's value");
height.value = width.value;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", are we the same thing now? \n");
System.out.println("[3] Assign to height's value an integer other than width's value");
height.value = 9;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", we are different things yet! \n");
System.out.println("[4] Assign to height the width object");
height = width;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", are we the same thing now? \n");
System.out.println("[5] Assign to height's value an integer other than width's value");
height.value = 9;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", we are the same thing now! \n");
System.out.println("[6] Assign to height a new MyInteger and an integer other than width's value");
height = new MyInteger();height.value = 1;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", we are different things again! \n");}}
这是我运行的输出:
Assignment operator evaluation using two MyInteger objects named height and width
[1] Assign distinct integers to height and width values-> height is 9 and width is 1, we are different things!
[2] Assign to height's value the width's value-> height is 1 and width is 1, are we the same thing now?
[3] Assign to height's value an integer other than width's value-> height is 9 and width is 1, we are different things yet!
[4] Assign to height the width object-> height is 1 and width is 1, are we the same thing now?
[5] Assign to height's value an integer other than width's value-> height is 9 and width is 9, we are the same thing now!
[6] Assign to height a new MyInteger and an integer other than width's value-> height is 1 and width is 9, we are different things again!
package com.asok.cop.example.task;public class Example {int data = 50;
void change(int data) {data = data + 100;// changes will be in the local variableSystem.out.println("after add " + data);}
public static void main(String args[]) {Example op = new Example();System.out.println("before change " + op.data);op.change(500);System.out.println("after change " + op.data);}}
输出:
before change 50after add 600after change 50
正如Michael在评论中所说:
对象仍然按值传递,即使对它们的操作表现得像引用传递。考虑void changePerson(Person person){ person = new Person(); },调用者对人对象的引用将保持不变。对象本身按值传递,但它们的成员可能会受到更改的影响。要成为真正的引用传递,我们必须能够将参数重新分配给一个新对象,并让更改反映在调用者中。
using namespace std;#include <iostream>
void change (char *&str){ // the '&' makes this a reference parameterstr = NULL;}
int main(){char *str = "not Null";change(str);cout<<"str is " << str; // ==>str is <null>}
Java通过值示例传递“Java引用”
public class ValueDemo{
public void change (String str){str = null;}
public static void main(String []args){ValueDemo vd = new ValueDemo();String str = "not null";vd.change(str);System.out.println("str is " + str); // ==> str is not null!!// Note that if "str" was// passed-by-reference, it// WOULD BE NULL after the// call to change().}}
program passByRefDemo;typeiptr = ^integer;varptr: iptr;
procedure setToNil(var ptr : iptr);beginptr := nil;end;
beginnew(ptr);ptr^ := 10;setToNil(ptr);if (ptr = nil) thenwriteln('ptr seems to be nil'); { ptr should be nil, so this line will run. }end.
class Apple {private double weight;public Apple(double weight) {this.weight = weight;}// getters and setters ...
}
然后,当您将此类的实例传递给main方法时:
class Main {public static void main(String[] args) {Apple apple = new Apple(3.14);transmogrify(apple);System.out.println(apple.getWeight()+ " the goose drank wine...";
}
private static void transmogrify(Apple apple) {// does something with apple ...apple.setWeight(apple.getWeight()+0.55);}}
哦…但你可能知道,当你做这样的事情时,你对会发生什么感兴趣:
class Main {public static void main(String[] args) {Apple apple = new Apple(3.14);transmogrify(apple);System.out.println("Who ate my: "+apple.getWeight()); // will it still be 3.14?
}
private static void transmogrify(Apple apple) {// assign a new apple to the reference passed...apple = new Apple(2.71);}
}
public class PrimitiveTypeExample {public static void main(string[] args) {int num = 10;System.out.println("Value before calling method: " + num);printNum(num);System.out.println("Value after calling method: " + num);}public static void printNum(int num){num = num + 10;System.out.println("Value inside printNum method: " + num);}}
输出为:调用方法前的值:10printNum方法内的值:20调用方法后的值:10
int num=10;->这会在正在运行的线程的Stack中为“int”分配内存,因为它是一种原始类型。现在当调用printNum(…)时,会在同一线程中创建一个私有堆栈。当“num”传递给此方法时,会在方法堆栈框架中创建“num”的副本。num=num+10;->这会增加10并修改方法堆栈框架中的int变量。因此,方法栈框架之外的原始num保持不变。
String name="Mehrose"; // name referencing to 100
ChangeContenet(String name){name="Michael"; // refernce has changed to 1001
}System.out.print(name); //displays Mehrose
public class PassByValue {public static void main(String[] args) {Test t = new Test();t.name = "initialvalue";new PassByValue().changeValue(t);System.out.println(t.name);}
public void changeValue(Test f) {f.name = "changevalue";}}
class Test {String name;}
public class PassByValue {public static void main(String[] args) {Test t = new Test();t.name = "initialvalue";new PassByValue().changeRefence(t);System.out.println(t.name);}
public void changeRefence(Test f) {f = null;}}
class Test {String name;}
public class Test{private static void needValue(SomeObject so) throws CloneNotSupportedException{SomeObject internalObject = so.clone();so=null;
// now we can edit internalObject safely.internalObject.set(999);}public static void main(String[] args){SomeObject o = new SomeObject(5);System.out.println(o);try{needValue(o);}catch(CloneNotSupportedException e){System.out.println("Apparently we cannot clone this");}System.out.println(o);}}
public class SomeObject implements Cloneable{private int val;public SomeObject(int val){this.val = val;}public void set(int val){this.val = val;}public SomeObject clone(){return new SomeObject(val);}public String toString(){return Integer.toString(val);}}
public static void main(String[] args) {Dog aDog = new Dog("Max");Dog oldDog = aDog;
// we pass the object to foofoo(aDog);// aDog variable is still pointing to the "Max" dog when foo(...) returnsaDog.getName().equals("Max"); // trueaDog.getName().equals("Fifi"); // falseaDog == oldDog; // true}
public static void foo(Dog d) {d.getName().equals("Max"); // true// change d inside of foo() to point to a new Dog instance "Fifi"d = new Dog("Fifi");d.getName().equals("Fifi"); // true}
/**** @author Sam Ginrich** All Rights Reserved!**/public class JavaIsPassByValue{
static class SomeClass{int someValue;
public SomeClass(int someValue){this.someValue = someValue;}}
static void passReferenceByValue(SomeClass someObject){if (someObject == null){throw new NullPointerException("This Object Reference was passed by Value,\r\n that's why you don't get a value from it.");}someObject.someValue = 49;}
public static void main(String[] args){SomeClass someObject = new SomeClass(27);System.out.println("Here is the original value: " + someObject.someValue);
passReferenceByValue(someObject);System.out.println("\nAs ´Java is pass by value´,\r\n everything without exception is passed by value\r\n and so an object's attribute cannot change: "+ someObject.someValue);
System.out.println();passReferenceByValue(null);}
}
从输出中可以很容易地看出,在Java一切都是按值传递的,如此简单!
Here is the original value: 27
As ´Java is pass by value´,everything without exception is passed by valueand so an object´s attribute cannot change: 49
'Exception in thread "main" java.lang.NullPointerException: This Object Reference was passed by value,that´s why you don´t get a value from it.at JavaIsPassByValue.passReferenceByValue(JavaIsPassByValue.java:26)at JavaIsPassByValue.main(JavaIsPassByValue.java:43)
public class Main{public static void main(String[] args){//Original value of 'x' will remain unchanged// in case of call-by-value
int x = 5;System.out.println( "Value of x before call-by-value: " + x);// 5
processData(x);System.out.println("Value of x after call-by-value: " + x);// 5}public static void processData(int x){x=x+10;}}