Skip to the content.
Intro Primitive Types Reference Types Stack and Heap Code Example Quiz

Unit 1 - Reference Types

An overview of Reference Types

Refrence Types

Reference types in Java include classes, arrays, and interfaces. Unlike primitive types, reference types store addresses (references) to objects rather than the objects themselves.

Classes

  • Create complex data structures by grouping variables and methods.

Example:

class Person {
    String name;
    int age;
}
Person person = new Person(); // `person` reference in stack, `Person` object in heap

Arrays

  • Collections of variables of the same type.

Example:

int[] numbers = new int[5]; // `numbers` reference in stack, array in heap

Popcorn Hack

public class Main {
    public static void main(String[] args) {
        // Create a reference type variable of type String
        String myString = "Hello, World!";
        
        // Create a reference type variable of type Array
        int[] myArray = new int[] {1, 2, 3, 4, 5};

        // Print the values
        System.out.println(myString);

        // Print the array manually
        System.out.print("[");
        for (int i = 0; i < myArray.length; i++) {
            System.out.print(myArray[i]);
            if (i < myArray.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }
}

Main.main(null);

Hello, World!
[1, 2, 3, 4, 5]