Everything About Non Primitive Data Types in Java

Everything About Non Primitive Data Types in Java

6 mins readComment
Esha
Esha Gupta
Associate Senior Executive
Updated on Sep 3, 2024 13:47 IST

Have you ever wondered how Java handles complex data structures and supports object-oriented programming? Non-primitive data types like classes, arrays, and interfaces enable the creation and manipulation of objects, storage of references to dynamically allocated memory, and integration of behaviours and states that improve application stability. Let's understand more!

Data types in Java specify the different sizes and values that can be stored in the variable. There are two main types of data types in Java, which are primitive data types and non-primitive data types in Java. In this blog, we will focus on understanding non-primitive data types in Java!

Check out Java courses here!

What are Non-Primitive Data Types in Java?

Non-primitive data types in Java, also known as reference types, refer to objects and arrays that are not predefined in the language like primitive types are. Unlike primitive types that hold their values directly and have a fixed size, non-primitive types hold references to objects, which can vary in size and are stored on the heap.

All About Primitive Data Types in Java

Here are the main types of non-primitive data types in Java:

1. Classes

  • User-Defined Classes: You can create your own classes, which define the properties and behaviours of objects.
  • Predefined Classes: Java comes with a multitude of built-in classes within the Java API, such as String, System, and Thread.

2. Arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created, and each item in an array is called an element.

3. Interfaces

Interfaces are abstract types that allow you to specify a group of related methods that classes must implement. They are used to enforce certain behaviours in classes that declare that they implement the interfaces, such as List and Map.

 

For Example, 

Problem Statement: Imagine you're developing a system for a library to manage book loans. The system needs to keep track of all the books, patrons (people who borrow books), and their borrowing histories. This example will demonstrate how non-primitive data types in Java, such as classes, arrays, and enums, can be effectively utilized in this context.


 
import java.util.ArrayList;
// Enum to represent the genre of a book
enum Genre {
FICTION, NONFICTION, SCIENCE, HISTORY, FANTASY
}
// Class to represent a Book
class Book {
String title;
String author;
Genre genre;
public Book(String title, String author, Genre genre) {
this.title = title;
this.author = author;
this.genre = genre;
}
public String toString() {
return title + " by " + author + " (" + genre + ")";
}
}
// Class to represent a Patron (library user)
class Patron {
String name;
ArrayList<Book> borrowedBooks;
public Patron(String name) {
this.name = name;
this.borrowedBooks = new ArrayList<>();
}
// Method to borrow a book
void borrowBook(Book book) {
borrowedBooks.add(book);
}
// Method to display borrowed books
void displayBorrowedBooks() {
System.out.println(name + " has borrowed:");
for (Book book : borrowedBooks) {
System.out.println(book);
}
}
}
// Main class to run the library system
public class LibrarySystem {
public static void main(String[] args) {
// Creating books
Book book1 = new Book("1984", "George Orwell", Genre.FICTION);
Book book2 = new Book("Cosmos", "Carl Sagan", Genre.SCIENCE);
// Creating a patron
Patron patron = new Patron("Esha");
patron.borrowBook(book1);
patron.borrowBook(book2);
// Display borrowed books
patron.displayBorrowedBooks();
}
}
Copy code

Output

Esha has borrowed:
1984 by George Orwell (FICTION)
Cosmos by Carl Sagan (SCIENCE)

Here,

  • Genre (Enum): Used to categorize books into predefined genres, making it easier to manage and search through the library's collection.
  • Book (Class): Represents a book with properties like title, author, and genre. This class uses the enum and strings (both non-primitive types).
  • Patron (Class): Represents a library user, with a method to borrow books and store them in an ArrayList, demonstrating the use of another non-primitive type, the ArrayList, which is part of Java's collection framework.
  • ArrayList<Book>: Used to store a dynamic list of borrowed books for each patron. Unlike an array, it can dynamically adjust its size.

This system makes effective use of non-primitive data types to handle complex data structures and relationships, such as a patron's collection of borrowed books and categorizing books by genre. The use of these types enhances the functionality, maintainability, and scalability of the Java application.

 An enum (short for enumeration) in Java is a special type of class that defines a collection of constants. Enums are a powerful feature that provide a way to define sets of named values in a type-safe manner. This means that an instance of an enum can hold only one of the predefined constants, which makes the code easier to read and less error-prone. It is one of the non-primitive data types!

Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
6 weeks
β‚Ή15 K
3 months
β‚Ή2.05 K
3 months
– / –
170 hours
β‚Ή5.4 K
1 month
– / –
6 months
– / –
2 months
β‚Ή17 K
3 months
β‚Ή5.5 K
1 month

Difference Between Primitive and Non-Primitive Data Types in Java

Feature

Primitive Data Types

Non-Primitive Data Types (Reference Types)

Basic Definition

Simple data types with a fixed size and not composed of other data types.

Complex objects or arrays that may consist of various data types and methods.

Memory Allocation

Stored directly in memory. The value is stored on the stack.

Stored in the heap. Only the reference/address is stored on the stack.

Size

Fixed size.

Variable size, depending on the elements or fields they contain.

Default Value

Have default values (e.g. 0 for int, false for boolean).

Default to null when not initialized.

Examples

int, double, char, boolean

String, Array, Class, Interface

Operations

Supports basic arithmetic and logical operations.

Can perform operations defined by methods and can manipulate objects.

Usage

Ideal for arithmetic and logical operations where memory efficiency is critical.

Used to build the functionalities of applications using methods, constructors, and by storing various states.

Storage Location

Stack

Heap

Speed

Fast access due to direct storage.

Slower access due to indirection (need to reference the heap).

Flexibility

Less flexible, fixed functionality.

More flexible and capable of representing complex data structures and behaviours.

Thus, non-primitive data types are important to learn in Java programming. They offer a broad range of functionalities that are crucial for today’s software development needs. 

Understanding Variables in Java

Learning Literals in Java

All About Java Syntax

FAQs

What exactly are non-primitive data types in Java?

 Non-primitive data types in Java, also known as reference types, include any data type that refers to an object rather than directly holding a value. They include classes, interfaces, arrays, and enums. Unlike primitives, reference types store a memory address (reference) that points to the location in memory where the actual data is stored, typically on the heap.

Why use non-primitive data types instead of primitives?

Non-primitive data types are used for more complex data structures and functionalities beyond the capabilities of primitive types. They can represent a collection of data, support methods (functions), and provide mechanisms for data encapsulation and inheritance. They are essential for object-oriented programming, allowing for the creation of complex, modular, and reusable code.

Can non-primitive types be initialized with null?

Yes, non-primitive types can be initialized to null. In Java, null signifies the absence of a data value. For reference types, setting an object reference to null indicates that it is not currently pointing to any object.

How does Java manage memory for non-primitive data types?

Java uses the heap to manage the memory allocation for non-primitive data types. Objects are created and stored in the heap, and Java's garbage collector automatically removes objects that are no longer being used, freeing up memory space. This helps in managing resources efficiently, especially in large applications.

What are some examples of non-primitive data types in real-world Java applications?

In real-world applications, non-primitive data types play a critical role. For example:

  • Classes like String and File are used extensively for handling textual data and file management.
  • Arrays and ArrayLists are used for storing and managing collections of elements, such as customer records in a database application.
  • Interfaces like List and Map define contracts for data structures that can be implemented in various ways depending on the specific requirements, such as LinkedList or HashMap.
  • Enums are used for fixed sets of constants like directions (NORTH, SOUTH, EAST, WEST) or days of the week, adding readability and safety to code.
About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio