BAEL-1725 Java Pass-by-reference vs Pass-by-value - First commit (#4058)

* BAEL-1725 Java Pass-by-reference vs Pass-by-value - First commit

* updated test cases
This commit is contained in:
ramansahasi 2018-04-23 20:27:02 +05:30 committed by maibin
parent dba41e16b0
commit 5f1b1b0b0d
4 changed files with 109 additions and 0 deletions

View File

@ -0,0 +1,27 @@
package com.baeldung.parameterpassing;
public class NonPrimitives {
public static void main(String[] args) {
FooClass a = new FooClass(1);
FooClass b = new FooClass(1);
System.out.printf("Before Modification: a = %d and b = %d ", a.num, b.num);
modify(a, b);
System.out.printf("\nAfter Modification: a = %d and b = %d ", a.num, b.num);
}
public static void modify(FooClass a1, FooClass b1) {
a1.num++;
b1 = new FooClass(1);
b1.num++;
}
}
class FooClass {
public int num;
public FooClass(int num) {
this.num = num;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.parameterpassing;
public class Primitives {
public static void main(String[] args) {
int x = 1;
int y = 2;
System.out.printf("Before Modification: x = %d and y = %d ", x, y);
modify(x, y);
System.out.printf("\nAfter Modification: x = %d and y = %d ", x, y);
}
public static void modify(int x1, int y1) {
x1 = 5;
y1 = 10;
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.parameterpassing;
import org.junit.Assert;
import org.junit.Test;
public class NonPrimitivesUnitTest {
@Test
public void whenModifyingObjects_thenOriginalObjectChanged() {
Foo a = new Foo(1);
Foo b = new Foo(1);
// Before Modification
Assert.assertEquals(a.num, 1);
Assert.assertEquals(b.num, 1);
modify(a, b);
// After Modification
Assert.assertEquals(a.num, 2);
Assert.assertEquals(b.num, 1);
}
public static void modify(Foo a1, Foo b1) {
a1.num++;
b1 = new Foo(1);
b1.num++;
}
}
class Foo {
public int num;
public Foo(int num) {
this.num = num;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.parameterpassing;
import org.junit.Assert;
import org.junit.Test;
public class PrimitivesUnitTest {
@Test
public void whenModifyingPrimitives_thenOriginalValuesNotModified() {
int x = 1;
int y = 2;
// Before Modification
Assert.assertEquals(x, 1);
Assert.assertEquals(y, 2);
modify(x, y);
// After Modification
Assert.assertEquals(x, 1);
Assert.assertEquals(y, 2);
}
public static void modify(int x1, int y1) {
x1 = 5;
y1 = 10;
}
}