For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!
Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.
class A { int a,int b; } class B { public static void main(String args[]) { A ob = new A(); ob.a = 10; ob.b = 20; System.out.println("Before swapping "+ob.a+" "+ob.b); swap(ob); System.out.println("After swapping "+ob.a+" "+ob.b); } public static void swap(A obj) { int temp = obj.a; obj.a = obj.b; obj.b = temp; } }
tmp = a; a = b; b = tmp;
class A { int a; int b; public static void main(String[] args) { // obj is a reference that "points" to an instance of A A obj = new A(); // The reference is passed, but it is passed by value because // the value of "obj" is copied. swap(obj); System.out.println(obj.a); System.out.println(obj.b); } static void swap(A arg) { // The variable "arg" is a reference that points to an instance of A // It's value has been copied from "obj" when it was passed in the // main method. Modifying "arg" will not modify "obj". // This is not modifying "arg", it is dereferencing "arg" and modifying // the value of the variables "a" and "b" of the instance of A that "arg" // points to which would be the same as the instance "obj" points to. arg.a = 10; arg.b = 20; // This modifies the value of "arg" to point at a new instance of A // This would not affect "obj", they would now point at two different // objects arg = new A(); // Does not affect "obj" // This has no effect on "obj" because we're changing the values of // a and b on a different instance of A arg.a = 30; arg.b = 40; } }
class Foo { String str_; } ... void m1(String str) { str = "abc"; } void m2(Foo foo) { foo.str_ = "xyz"; } String s = "ORIGINAL"; Foo f = new Foo(); foo.str_ = "ORIGINAL"; m1(s); m2(f); System.out.println(s); // prints "ORIGINAL" System.out.println(f.str_); // prints "xyz"
// Objects are passed by reference Class Test{ int a,b; ......
// Objects are passed by reference> ....
// Objects are passed by reference>
main() { int a=10,b=20; swap(a,b); printf("%d %d",a,b); } swap(int a,int b) { int t=a; a=b; b=t; }
main() { int a=10,b=20; swap(&a,&b); printf("%d %d",a,b); } swap(int *a,int *b) { int t=*a; *a=*b; *b=t; }
main() { int a=10,b=20; swap(a,b); printf("%d %d",a,b); a,int b) int t=a; a=b; b=t; e] Above is pass-by-value;
main() { int a=10,b=20; swap(&a,&b); printf("%d %d",a,b); *a,int *b) int t=*a; *a=*b; *b=t; e] Above is pass-by-reference.
swap(&a,&b);
void primPtrByVal(int* param1, int* param2) { int* tmp = param1; param1 = param2; param2 = tmp; }
int i = 1; int j = 2; primPtrByVal(&i, &j);
void primByRef(int& param1, int& param2) { int tmp = param1; param1 = param2; param2 = tmp; }
int i = 1; int j = 2; primByRef(i, j);