Define and use composite data types

13.1 User‑Defined Data Types 📦

What is a User‑Defined Data Type?

A user‑defined data type (UDT) lets you bundle several related values together into a single logical unit. It’s like creating your own LEGO set: you decide which bricks (values) belong together and how they’re connected.

Why Use Composite Data Types?

  • Organises code – keeps related data together.
  • Improves readability – a Student type is clearer than separate name, age, grade variables.
  • Encourages re‑use – the same type can be used in many places.

Defining a Composite Data Type in Java

In Java, a composite data type is usually defined with a class or record. Below is a simple class that represents a book.

public class Book {
    private String title;
    private String author;
    private int pages;

    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }

    // Getters
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public int getPages() { return pages; }
}

If a Book has 3 fields, its size is:

$$|Book| = |title| + |author| + |pages|$$

Using the Data Type

  1. Create an instance: Book myBook = new Book("1984", "George Orwell", 328);
  2. Access its data: String title = myBook.getTitle();
  3. Store many books in an array or ArrayList for collections.

Exam Tip Box 🎯

Tip: When the question asks you to define a data type, include:
  • Field names and types
  • Constructor(s)
  • Getter methods (or public fields if allowed)
Tip: For record types, remember the concise syntax: record Point(int x, int y) {}.

Example: Contact Record

Field Type Description
name String Full name of the person
phone String Telephone number
email String Email address

Quick Recap

  • UDTs bundle related data.
  • Define with class or record.
  • Include fields, constructor, and access methods.
  • Use in collections for multiple instances.

Remember: A well‑designed data type is like a well‑built LEGO set – it’s easy to use, easy to understand, and can be reused in many projects. 🚀

Revision

Log in to practice.

3 views 0 suggestions