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:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user