Thursday, September 29, 2016

Java - Reference Data Type


Several weeks ago, we learned primitive data type, which is some basic knowledge of Java. For example, some data types we often use in our programming assignments, such as char, boolean, int, double, are all primitive data type. However, in addition to primitive data type, there is another important type, which is called reference data type.

A reference type is a data type which is based on a class rather than on one of the primitive types that are built in to the Java language. All objects are reference date types. To declare a variable using a reference type, you simply list the class name as the data type. See the following example:
Date d = new Date(2, 17, 1948);
This statement creates a reference variable d that refers to a Date object. The value of d is the address in memory of that object.

What we should pay attention to is the difference between primitive data type and reference data type. Consider the statements:
int a = 1;
int b = a;
If in later statements, either a or b is changed, the other is not affected. For example,
int a = 2;
Then, a becomes 2 but b is still 1.

However, reference type is different. Consider the following two statements:
Date d = new Date(2, 17, 1948);
Date birthday = d;
The second statement will not create a new object. What is true is that the object has two references in this case. Thus, the statement
d.changeDate();  will automatically change the object referred to by birthday as well.

---------------------------------------------------------------------------------

Writing References:
1.http://www.dummies.com/programming/java/reference-types-in-java/
2.Barron's AP Computer Science A
Picture Reference:
https://www.ntu.edu.sg/home/ehchua/programming/java/images/OOP_PrimitiveVsClass.png

1 comment:

  1. I find reference data and objects particularly useful when we have complex programming projects. Creating new objects with their owns states and behaviors would make our code much clearer! Although we haven't studied much about reference data and objects in class, I found your article relevant to what Dr. Jory said about pointer today. I also like the distinction you made about object having two references versus creating new objects.

    ReplyDelete