Sub topic 2
Primitive and Reference Types
In Java, every variable has a type. A type tells Java what kind of value the variable can hold. Java types fall into two groups: primitive types and reference types.
A primitive variable holds a simple value directly. A reference variable holds a reference, which identifies an object. An object is a piece of data that a program can use.
Primitive types
Java has eight primitive types:
byte,short,int, andlonghold whole numbers.floatanddoublehold numbers that can have decimal parts.charholds a character value.booleanholdstrueorfalse.
For example, int count = 3; creates an int variable named count and gives it the value 3.
When you copy a primitive value into another variable, each variable has its own value. Changing one does not change the other.
Reference types
A reference type describes the kind of object a variable can refer to. For example, String is a reference type for text. Even though you can write text directly in Java, a String variable is not a primitive variable.
Copying a reference is different from copying a primitive value. Both reference variables can refer to the same object. If that object can be changed, a change made through one reference can be seen through the other.
An array is an object that holds a fixed number of values. The following example uses an array so you can see what happens when two references share one object.
Worked example
Save this program as PrimitiveReferenceDemo.java. In the program, int[] is the type for an array of int values. The position [0] means the first place in the array.
class PrimitiveReferenceDemo {
public static void main(String[] args) {
int count = 3;
int copy = count;
copy = 7;
int[] first = {3};
int[] second = first;
second[0] = 9;
System.out.println(count);
System.out.println(copy);
System.out.println(first[0]);
System.out.println(second[0]);
}
}Compile and run it from the folder containing the file:
javac PrimitiveReferenceDemo.java
java PrimitiveReferenceDemoThe output is:
3
7
9
9The primitive variables count and copy have separate values. Changing copy leaves count at 3.
The reference variables first and second refer to the same array. Changing its first value through second also changes what you see through first.
A reference to nothing
A reference variable can also hold null. This special value means it does not refer to an object.
Exercise
If you copy an int value into another int variable and then change the copy, does the first variable change? What if you copy a reference and change the shared object?
Show answer
Changing the int copy does not change the first variable. With copied references, both can refer to the same object, so a change to that object can be seen through either reference.