top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Non-Primitive Data Types in Java

Introduction

Non-primitive data types in Java are data types that are not integrated and allow more complicated and configurable structures and behaviors. They include classes, interfaces, arrays, and enums, which let developers build and operate objects with multiple values and references.

Overview

Non-primitive data types are user-defined data types beyond the built-in or fundamental ones. These data types, including classes, interfaces, and arrays, enable the creation of customized structures and behaviors.

Non-primitive data types in Java provide versatility by allowing developers to build their data structures and operate complicated objects.

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).

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 are not built into or specified by the language. These data types are user-created and are either derived from primitive data types or composite types.

Non-primitive data types in Java allow users to create sophisticated and customizable data structures and behaviors, giving the programming language flexibility and extensibility.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *