0
0
Javaprogramming~5 mins

Reference data types in Java

Choose your learning style9 modes available
Introduction

Reference data types let you work with objects and store their addresses instead of simple values. This helps you manage complex data like text, lists, or custom things.

When you want to store and manipulate text using String objects.
When you need to create and use custom objects like a Person or Car.
When you want to work with collections like arrays or ArrayLists.
When you want to pass objects to methods and change their contents.
When you want to use built-in classes like Scanner to read input.
Syntax
Java
ClassName variableName = new ClassName();

Reference variables store the address of the object, not the actual data.

You create an object using the new keyword followed by the class constructor.

Examples
This creates a String object holding the text "Alice" and stores its reference in name.
Java
String name = new String("Alice");
This creates a Scanner object to read user input from the keyboard.
Java
Scanner input = new Scanner(System.in);
This creates an array object to hold 5 integers and stores its reference in numbers.
Java
int[] numbers = new int[5];
Sample Program

This program creates a String object and an integer array object. It prints the greeting and then prints each score from the array.

Java
import java.util.Scanner;

public class ReferenceExample {
    public static void main(String[] args) {
        String greeting = new String("Hello, world!");
        System.out.println(greeting);

        int[] scores = new int[3];
        scores[0] = 90;
        scores[1] = 85;
        scores[2] = 78;

        System.out.println("Scores:");
        for (int score : scores) {
            System.out.println(score);
        }
    }
}
OutputSuccess
Important Notes

Reference variables can be set to null to mean they point to no object.

Two reference variables can point to the same object, so changing the object via one variable affects the other.

Primitive types like int or double store actual values, not references.

Summary

Reference data types store addresses to objects, not the actual data.

Use new to create objects and assign their references to variables.

Reference types let you work with complex data like text, arrays, and custom objects.