Non-Primitive Data Types in Java

In the Java programming language, data types are broadly categorized into two groups: primitive data types and non-primitive data types.

Non-primitive data types are those data types in Java that are used to store multiple values. These data types are also called user-defined data types because they are created by users or programmers.

Non-primitive data types do not store the actual value or data directly. Actually, they store a reference or memory address where the actual data is stored. In other words, when you define non-primitive data types, it refers to the memory location in the heap memory where the data is located.

For this reason, non-primitive data types are also called reference data types or object-only reference variables because they store the memory address of an object. Class, interface, and arrays are the most common examples of reference data types in Java.

Key Characteristics of Non-Primitive Data Types in Java

There are several important characteristics of non-primitive data types in Java. They are as:

  • Size Variability: Unlike primitive types, non-primitive types do not have a fixed size because the size of a non-primitive data type does not depend on the data type. Non-primitive data types have all the same size.
  • Complex Structures: They can store multiple values or represent complex structures like strings, arrays, data structures, and objects.
  • Methods and Operations: Many non-primitive types in Java come with built-in methods that perform specific operations.
  • Default Value: The default value for non-primitive data types is null.
  • OOPs Features: Non-primitive types, such as classes and interfaces, can leverage the feature of object-oriented features (OOPs), such as inheritance, encapsulation, and polymorphism.

Types of Non-Primitive Data Types in Java

We can broadly categorize non-primitive data types as follows:

  • Strings
  • Arrays
  • Classes
  • Interfaces
  • Enums
  • Collections and Maps

Let’s understand into each of these types in detail.

Non-primitive data types in Java

1. Strings

Strings are one of the most commonly used non-primitive data types in Java programming language. A String represents a sequence of characters. For example, “Hello World, “Core Java”, etc. A string is implemented as a class in Java. You can create a string like this:

String str = "Core Java Book";

Key Features of Strings

  • Immutability: Strings in Java are immutable in nature, meaning that their value cannot be changed once created.
  • String Pool: Java optimizes the usage of memory by maintaining a pool of string literals.
  • Rich API: The String class provides several methods for manipulation, such as concat(), substring(), indexOf(), replace(), etc. You will learn about it in the string chapter.

Example 1:

public class StringExample {
  public static void main(String[] args) {
  // Create string literals. 
     String greeting = "Hello";
     String name = "World";
     String message = greeting + " " + name + "!";
     System.out.println(message); 
  }
}
Output:
     Hello World!

2. Arrays

An array is a container that holds a fixed number of values of the same data type in a single data structure. It is one of the simplest non-primitive data types in Java. Arrays are reference data types in Java because an array variable stores the reference or memory address to the array object in the memory. The general syntax to create an array is as:

int[] = new int[50]; // 'num' is a reference to an array of integers.

Key Characteristics of Arrays

  • Indexed Storage: Elements in an array are stored in contiguous memory locations and accessed using an index starting from 0.
  • Fixed Size: Once an array is created, its size cannot be changed.
  • Multidimensional Arrays: Java supports both one-dimensional and multidimensional arrays, such as 2D arrays.

Example 2:

public class ArrayExample {
 public static void main(String[] args) {
    int[] numbers = {1, 2, 3, 4, 5};
    for (int num : numbers) {
        System.out.println(num);
    }
  }
}
Output:
     1
     2
     3
     4
     5

3. Classes

A class defines a blueprint for creating an object in Java, which is an instance of the class. It encapsulates both data and methods that operate on that data. A class is a user-defined data type that allows you to create a custom data type, making it possible to model real-world entities and implement complex behaviours.

When you create an object (instance) of a class, a reference variable is used to store the memory address of that object. The syntax to define a class and create an instance of class is as follows:

// Create a class.
class MyClass {
  // Class body
}
// Create an object of class.
MyClass obj = new MyClass();

Example 3:

// Create a class named Car.
class Car {
   String brand;
   int year;

   void displayInfo() {
      System.out.println("Brand: " + brand + ", Year: " + year);
   }
}
public class ClassExample {
public static void main(String[] args) {
// Create an instance of class Car.
   Car car = new Car();
   car.brand = "Toyota";
   car.year = 2021;
   car.displayInfo(); // Calling method.
  }
}
Output:
      Brand: Toyota, Year: 2021

4. Interfaces

An interface is a reference data type in Java that defines contracts for classes to implement. In Java, an interface reference variable can store objects of any class that implements the interface. This is a key feature of object-oriented programming in Java, enabling polymorphic behavior.

An interface defines a contract by specifying a set of abstract methods that any class implementing the interface must provide concrete implementations for. All methods in an interface are abstract by default. A class can implement multiple interfaces. Since Java 8 version, interfaces can include default methods with implementation.

The general syntax to define an interface is Java is as follows:

interface MyInterface {
  void myMethod();
}
class MyImplementation implements MyInterface {
  public void myMethod() {
    // Implementation
  }
}
MyInterface interfaceRef = new MyImplementation(); // Here, interfaceRef is a reference variable that is pointing to an object of class MyImplementation. 

Example 4:

// Define an interface named Animal.
interface Animal {
    void sound();
}
// Create a class named Dog that implements Animal using implement keyword.
class Dog implements Animal {
 // Implementation.
    public void sound() {
        System.out.println("Woof Woof");
    }
}
// Create another class named Cat that implements Animal.
class Cat implements Animal {
    public void sound() {
        System.out.println("Meow");
    }
}

public class InterfaceReferenceExample {
public static void main(String[] args) {
    Animal animal1 = new Dog();  // Here, interface reference animal1 points to a Dog object
    Animal animal2 = new Cat(); // Here, interface reference animal2 points to a Cat object
        
    animal1.sound(); // Calling method.
    animal2.sound(); // Calling method.
  }
}
Output:
      Woof Woof
      Meow

5. Enums

Enums are special reference data types that represent a group of constants. They are useful when a variable can take one of a predefined set of values. Enums provide type safety as well as built-in methods like values(), ordinal(), and name().

Example 5:

// Define enum named Day.
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class EnumExample {
public static void main(String[] args) {
   Day today = Day.FRIDAY;

// Calling values() method.
   for (Day day : Day.values()) {
            System.out.println(day);
   }

// Calling ordinal() method.
   System.out.println("Ordinal of " + today + ": " + today.ordinal());

// Displaying the current day.
   System.out.println("Today is: " + today.name());
  }
}
Output:
     MONDAY
     TUESDAY
     WEDNESDAY
     THURSDAY
     FRIDAY
     SATURDAY
     SUNDAY
     Ordinal of FRIDAY: 4
     Today is: FRIDAY

6. Collections and Maps

Collections framework in Java provides a set of classes and interfaces for storing and manipulating groups of objects. These are more dynamic and versatile as compared to arrays. Some of the key components of it are as:

  • List: Ordered collection. For example, ArrayList, LinkedList.
  • Set: Unordered collection with no duplicate elements. For example, HashSet, TreeSet.
  • Map: Collection of key-value pairs. For example, HashMap, TreeMap.
  • Queue and Deque: FIFO and double-ended queues. For example, PriorityQueue, ArrayDeque.

Example 6:

import java.util.ArrayList;
public class CollectionExample {
public static void main(String[] args) {
// Creating an object of ArrayList class.
  ArrayList<String> list = new ArrayList<>();

// Adding elements.
  list.add("Java");
  list.add("Python");
  list.add("C++");

// Iterating elements.
  for (String language : list) {
       System.out.println(language);
  }
 }
}
Output:
     Java
     Python
     C++

You will learn more about collections in the collections framework chapter.

Difference between Primitive and Non-primitive Data Types

The main difference between primitive and non-primitive data types in Java is as follows:

  • Primitive data types are predefined (already defined) in Java programming, whereas non-primitive types are created by the programmers and are not predefined in Java except string.
  • You can use non-primitive data types to call methods for performing certain operations, whereas primitive types cannot.
  • The default value of primitive data types is type specific, while non-primitive types can be null.
  • A primitive type starts with a lowercase, while a non-primitive type starts with an uppercase letter.
  • The size of primitive types, such as int, float, etc, depends on their specific data type and is fixed. For example, int is always 4 bytes in size. Whereas, the size of non-primitive types, such as string, array, object, can vary. However, a reference pointing to a non-primitive type (i.e. the memory address it holds) is typically constant.
AspectPrimitive TypesNon-Primitive Types
SizeFixedVariable
Default valueType-specificnull
OperationsLimited operationsRich methods and operations.
InheritanceNot applicableSupports inheritance and polymorphism.
Examplesint, double, booleanString, array, class.

These are the basic differences between primitive and non-primitive data types in Java that you should remember. You will learn about all non-primitive data types in the later chapters.

Please Share Your Love.

Leave a Reply

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