Reference Types vs Primitive Types

class Test {
	String x= "hello";
}

// make an object
Test myTest = new Test();

Test = name of the class
myTest = object reference variable
Test() = contractor of test

Snap 2014-04-21 at 12.52.41
Credit: screen shot from SlideNerd videos on youtube

myTest does not actually hold an object, it holds a REFERENCE to an abject, which is a memory location. The object itself is stored somewhere else – this is for efficiency of memory usage.

System.out.println(myTest);

will produce something like

Test@4u254por

4u254por is the memory location of the actual Test object.

If we say:

Test myTest = new Test();
Test yourTest = myTest;

Snap 2014-04-21 at 12.54.36
Credit: screen shot from SlideNerd videos on youtube

we are saying yourTest points to the same memory address as myTest.

PRIMITIVE TYPES

int y=15;

y and 15 are in the same place in memory. This is because primitive types require little storage to the reference and the value are stored in the same place.

Snap 2014-04-21 at 12.57.25
Credit: screen shot from SlideNerd videos on youtube

When you copy primitive types, the original and copy are independent values.

Take a look at the following:

Snap 2014-04-21 at 13.00.24
Credit: screen shot from SlideNerd videos on youtube

Here Vivs gives a good example using objects. Unlike primitive types, with objects, if we use =, and then use a method to change the variable in one object, change(), both object yourTest and myTest contain the same value of x.

Here is a code example of this:

public class TestMain {

	public static void main(String[] args) {
	
		
		// primitive data types
		int x=20;
		int y=10;
		System.out.println("x= "+x +" y= "+y);
		x=y;
		System.out.println("x= "+x +" y= "+y);
		y=5;
		System.out.println("x= "+x +" y= "+y);
		
		
		// object references
		Test myTest = new Test();
		System.out.println("myTest= "+myTest.message);
		Test anotherTest = new Test();
		System.out.println("anotherTest= "+anotherTest.message);
		
		Test copiedTest = myTest;
		System.out.println("copiedTest= "+copiedTest.message);
		
		copiedTest.change();
		System.out.println("myTest= "+myTest.message);
		System.out.println("anotherTest= "+anotherTest.message);
		System.out.println("copiedTest= "+copiedTest.message);
	}
}


class Test
{
	String message="hello!";
	
	public void change()
	{
		message="good bye";
	}

}

Outputs:

x= 20 y= 10
x= 10 y= 10
x= 10 y= 5
myTest= hello!
anotherTest= hello!
copiedTest= hello!
myTest= good bye
anotherTest= hello!
copiedTest= good bye

Leave a Reply