Non-Primitive Data Types in Java

Updated on 02/09/20255,276 Views

Non-Primitive Data Types in Java are user-defined or derived data types that allow developers to create complex structures. Unlike primitive types that store simple values, non-primitive types like classes, arrays, strings, objects, and interfaces store references and support multiple behaviors. These data types provide flexibility to handle data and implement object-oriented programming concepts effectively. 

This tutorial explains Non-Primitive Data Types in Java with clear definitions and examples. You will learn how arrays, strings, classes, and interfaces work, along with their key features and applications. We will also compare them with primitive types to highlight their differences. By the end, you will have a strong understanding of how to use non-primitive data types efficiently in Java programs. 

Looking to advance your Java framework skills? Check out upGrad’s Online Software Engineering Courses. Start today to strengthen your foundation and accelerate your career growth by learning JavaScript, Node.js, APIs, React, and more!

What Are Non-Primitive Data Types in Java? 

Non-Primitive Data Types in Java, also called reference or object data types, are not built into the language but created by programmers. Unlike primitive types that store simple values directly in memory, non-primitive types store references to objects.  

Boost your career growth by learning in-demand skills across Cloud, DevOps, AI, and Full Stack Development. Work on real-world projects, gain practical expertise, and learn directly from industry experts to stand out in the job market. 

  • Professional Certificate Program in Cloud Computing and DevOps 
  • AI-Powered Full Stack Development Course by IIITB
  • Future-Proof Your Tech Career with AI-Driven Full-Stack Development 

Examples include classes, objects, arrays, strings, and interfaces. These data types allow developers to build flexible, reusable, and more complex structures. They also support methods and behaviors, making them integral to object-oriented programming in Java. Non-primitive types provide the foundation for modeling real-world entities and solving advanced programming problems efficiently.

What Are Data Types in Java?

Data types in Java categorize and define the data types variables can store. Primitive data types in Java represent simple values such as boolean, byte, int, long, and char.

And each data type comes with specific ranges of values and tasks that users can perform.

1. Primitive Data Type

Primitive data types in programming languages are the language’s most essential types.

Primitive data types are directly supported by the hardware and have specific sizes and representations in memory. Primitive data are straightforward, meaning you cannot divide them into smaller pieces.

Primitive data types, unlike complex data types or objects, do not have methods or different properties associated with them. Primitive data types represent fundamental values such as characters, boolean values, or numbers.

2. Non-Primitive Data Types or Object Data Types

Non-primitive data types in Java are data types that are not pre-defined. They are instead built by the programmer using classes or structures. Non-primitive data types in javascript have multiple values or components and can have complex systems.

Primitive Data Types in Java

Primitive data types in Java are fundamental data types that hold simple values and have fixed sizes, some of the primitive data types are stated below:

i) Boolean

The Boolean data type is commonly used in conditional statements to control the flow of the program based on specific conditions. It is also used in Boolean expressions and logical operations to compare and make decisions.

Here is an example:

public class BooleanExample {
    public static void main(String[] args) {
        boolean isSunny = true;
        boolean isRaining = false;
        System.out.println("Is it sunny? " + isSunny);
        System.out.println("Is it raining? " + isRaining);
        if (isSunny) {
            System.out.println("Wear sunglasses!");
        } else {
            System.out.println("Carry an umbrella!");
        }
    }
}

ii) Byte

The byte data type in Java is a primitive data type used to represent signed 8-bit integer values. It ranges from -128 to 127. The byte data type refers to when memory conservation is a priority or when working with raw binary data or streams.

public class ByteExample {
    public static void main(String[] args) {
        byte number = 100;
        System.out.println("Number: " + number);
    }
}

iii) Char

The primitive char data type represents a single 16-bit Unicode character. Char can store any character, including letters, digits, symbols, and spaces.

iv) Short

The short primitive data type represents signed 16-bit integer values. It stores whole numbers within the range of -32,768 to 32,767.

The short data type is practical in scenarios where memory conservation is a concern or when working with smaller integer values that fit within its range.

v) Int

Int is a primitive data type that represents signed 32-bit integer values. Int ranges from -2,147,483,648 to 2,147,483,647 and is the most popular integer data type that is used in Java.

vi) Long

The long primitive data type represents signed 64-bit integer values and ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

It helps calculate large numbers or situations where the range of values exceeds the int data type limit.

vii) Float

The float data type is useful when precision is not the primary concern, and there is a need for a more comprehensive range of values with decimal points. It is suitable for scientific calculations, graphics, and audio processing scenarios.

viii) Double

The primitive double data type in Java represents double-precision 64-bit floating-point values. It can store decimal numbers more precisely than the float data type.

Double covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).

Also Read: Java Classes and Objects

Types of Non-Primitive Data Types

Non-primitive data types in Java include classes, arrays, interfaces, and more.

Some non-primitive data types examples are discussed below:

i) Class

In Java, a class is a blueprint or template for creating objects. It defines the structure, behavior, and state of objects. A class serves as a blueprint from which users can make multiple objects.

Let us understand classes properly with this example:

In this example, we define a class called Person, which has a private instance variable name of type String. The class also has a constructor to initialize the name and a getter method to retrieve the name value.

Inside the main method, we create an instance of the Person class and pass the name "Oreo" as an argument to the constructor. Then, we use the getter method to retrieve the name and print it to the console.

public class Person {
    private String name;
    public Person(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public static void main(String[] args) {
        Person person = new Person("Oreo");
        System.out.println("Person name: " + person.getName());
    }
}

ii) Object

An object is an instance of a class in Java. It represents a specific occurrence or realization of the class's structure and behavior. Objects have their own unique identity and can hold state and perform actions based on the defined behavior of the class.

Let us learn the function of objects with this example:

In this example, we declare a variable obj of type Object and assign it the value "Hello, World!".

The Object class is the root class in Java's class hierarchy, and it is a non-primitive data type that can hold references to any other type of object.

We use System.out.println() to print the value of obj to the console.

public class ObjectExample {
    public static void main(String[] args) {
        Object obj = "Hello, World!";
        System.out.println(obj);
    }
}

iii) String

Java uses a String class to represent character strings. Java uses strings to store and process text-based data. Since strings cannot be muted, users cannot alter their values post-formation.

Here is an example of using strings in Java:

In this example, we declare a variable message of type String and assign it the value "Hello, World!".

public class StringExample {
    public static void main(String[] args) {
        String message = "Hello, World!";
        System.out.println(message);
    }
}

iv) Array

Arrays have a fixed size, and users can use an index to access any element. Arrays offer a practical way to manage and store collections of data.

Here is an example of using arrays in Java:

In this example, we declare an array variable numbers of type int[] and initialize it with the values {1, 2, 3, 4, 5}.

Arrays in Java are used to store multiple values of the same type in a contiguous memory block.

We use System.out.println() to print the length of the array (numbers.length), the first element of the array (numbers[0]), and the last element of the array (numbers[numbers.length - 1]) to the console.

The array numbers has a length of 5, and we access and print the first element (1) and the last element (5) of the array.

Arrays in Java are zero-indexed, so the first element is accessed using index 0, and the last element is accessed using length - 1.

public class ArrayExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        System.out.println("Array length: " + numbers.length);
        System.out.println("First element: " + numbers[0]);
        System.out.println("Last element: " + numbers[numbers.length - 1]);
    }
}

v) Interface

An interface in Java is a collection of blueprints of linked methods that a class must install. It defines a collection of methods that users must provide a class before implementing the interface.

Here is an example of an interface in Java:

public interface Printable {
    void print();
}
public class InterfaceExample {
    public static void main(String[] args) {
        Printable printable = new Document();
        printable.print();
    }
}
public class Document implements Printable {
    @Override
    public void print() {
        System.out.println("Printing document...");
    }
}

In order for this program to work, we must make three separate files for these three portions of code, Printable.java, InterfaceExample.java and Document.java.

In the above example, we defined an interface called Printable, which declares a single method print().

The Printable interface serves as a contract, specifying that any class that implements it must provide an implementation for the print() method.

We then created a class called Document that implements the Printable interface and provides its implementation for the print() method.

Inside the main method of the InterfaceExample class, we created an instance of the Document class and assigned it to a variable of type Printable. This demonstrates the usage of the interface as a non-primitive data type.

Finally, we invoked the print() method on the Printable object, which calls the implementation provided by the Document class.

Difference between Primitive and Non-Primitive Data Types in Java

Primitive and non-primitive data types differ based on operations, storage, and methods.

A few of the many differences between primitive and non-primitive data types in Java are stated in the table below.

Aspect

Primitive Data Types

Non-Primitive Data Types

Definition

Basic data types provided by Java

Data types created by users

Storage

Store actual values

Store references to objects

Memory Size

Take up less memory

Take up more memory

Default Value

Have default values

The default value is 'null.'

Operations

Can perform arithmetic operations

Can perform complex operations

Wrapper Classes

Have corresponding wrapper classes (e.g., Integer, Boolean)

No wrapper classes

Mutability

Immutable

Mutable

Methods

No methods associated with them

Can have methods and behaviors

Examples

int, boolean, char

String, Object, Arrays, etc.

Conclusion

Non-Primitive Data Types in Java play a crucial role in building robust and flexible applications. Unlike primitive data types that store simple values directly, non-primitive types such as arrays, strings, objects, and interfaces hold references and support advanced operations. These data types allow developers to define reusable structures, encapsulate behavior, and model entities with greater accuracy.  

By using Non-Primitive Data Types in Java, programmers can implement object-oriented principles, design scalable systems, and handle complex data efficiently. Their versatility makes them essential for modern software development where flexibility, abstraction, and reusability are key.

FAQs

1. What are the examples of Java's non-primitive data types?

Strings, arrays, objects, and interfaces are some examples of non-primitive data types in Java.

2. What is the difference between primitive and non-primitive data types in Java?

Non-primitive data types are more complex in behavior and functions. Primitive data types are pre-defined, store actual values, and have a few functions.

3. What distinguishes a class from an object in Java?

A class serves as a model or template for building objects. An object is an instance of a class, signifying a detailed representation of the class’s structure and behavior.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow

FREE COURSES

Start Learning For Free

image
Pavan Vadapalli

Author|911 articles published

Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

Top Resources

Recommended Programs

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 10 AM to 7 PM

text

Indian Nationals

text

Foreign Nationals