Java is Pass-by-Value or Pass-by-Reference?

What's saved in Object Reference?

We can treat the Java Object will be managed in two parts:

 

  1. Obejct definition and its reference to Memory Heap which contains object's attribute and data contents.
  2. Data contents in memory heap which is known by Object by reference.

The following Junit test code prove this understanding.

 

	class TempString {
		private String temp;

		public TempString(String str) {
			this.temp = str;
		}

		public String getTemp() {
			return temp;
		}

		public void setTemp(String temp) {
			this.temp = temp;
		}
	}

	@Test
	public void testObjectReference() {
		TempString obj = new TempString("test");
		TempString objb = obj;

		obj = null;
		TempString objc = obj;
		assertNull(obj);
		assertNull(objc);
		assertNotNull(objb);
		assertEquals("test", objb.getTemp());
	}
 

Set Object to be NULL: Object=null

We can use the "Object=null" to release memory. But keep in mind, it is not "=null" operation itself make memory released. Garbage Collector will clean and release memory heap later if it found there is no any reference to the data (in memory heap).

 

List keep the Object reference but not object itself

From below test, we can know that: Collect keep the object reference to its memory heap.

 

	@Test
	public void testListKeepOriginalAfterSetObjectTobeNull() {
		TempString obj = new TempString("test");
		List<TempString> list = new ArrayList<TempString>();
		list.add(obj);

		obj = null;

		assertNull(obj);
		assertEquals("test", list.get(0).getTemp());

		List<String> list2 = new ArrayList<String>();
		String a = new String("StringObject");
		String b = "testPrimitive";
		list2.add(a);
		list2.add(b);
		a = null;
		b = null;
		assertEquals("StringObject", list2.get(0));
		assertEquals("testPrimitive", list2.get(1));

		List<Integer> list3 = new ArrayList<Integer>();
		Integer intA = new Integer(1);
		Integer intB = 5;
		list3.add(intA);
		list3.add(intB);
		intA = null;
		intB = null;
		assertNotNull(list3.get(0));
		assertEquals(1, list3.get(0).intValue());
	}

 

Java is Pass-by-Value or Pass-by-Reference?

To be Updated. Here I list the doc I found from Internet:

 

 

Clone your Java Object

To be Updated. Here I list the doc I found from Internet: 

 

你可能感兴趣的:(reference)