Value Type vs Reference Type

All the primitive types are value types, in other words, they hold a value. Unlike primitive types, an array is a reference type and String is also a reference type.

Values Type

package anote;

public class Main {
    public static void main(String[] args) {
        int theValue = 10;
        int anotherValue = theValue;

        System.out.println("theValue is " + theValue );
        System.out.println("anotherValue is " + anotherValue );

        anotherValue++;

        System.out.println("theValue is " + theValue );
        System.out.println("anotherValue is " + anotherValue );
    }
}
theValue is 10
anotherValue is 10
theValue is 10
anotherValue is 11

The value type is a single space in memory is allocated to store the value, thus the values directly holds the values.

the example (theValue and anotherValue) holds the values independently.

Reference type

package anote;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {

        int [] theArray = new int [5];
        int [] anotherArray = theArray;

        System.out.println("theArray is " + Arrays.toString(theArray));
        System.out.println("anotherArray is " + Arrays.toString(anotherArray));
        anotherArray[0] = 1;

        System.out.println("theArray is " + Arrays.toString(theArray));
        System.out.println("anotherArray is " + Arrays.toString(anotherArray));
    }
}
theArray is [0, 0, 0, 0, 0]
anotherArray is [0, 0, 0, 0, 0]
theArray is [1, 0, 0, 0, 0]
anotherArray is [1, 0, 0, 0, 0]

The Reference type, like array or classes. So whenever you see the new keywords that you are creating a new objects.

The reference type used by reference. The reference holds a reference or an address of the objects, but not objects itself. With reference types, we are using a reference to control the object in memory. So, we can not access the object directly.

Leave a Reply

Your email address will not be published.

ANOTE.DEV