Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Data Types in Java
3.
What are Non-Primitive Data Types?
3.1.
Syntax
4.
Types Of Non-Primitive Data Types in Java 
4.1.
1. Class
4.2.
2. Interface
4.3.
3. Array
4.4.
4. String
5.
Frequently Asked Questions
5.1.
What are the non-primitive data types?
5.2.
What data types are primitive in Java?
5.3.
How many non-primitive types are there in Java?
5.4.
Which are three types of primitive data used in Java?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Non Primitive Data Types in Java

Author Harshita Vyas
0 upvote

Introduction

Java is a powerful programming language with a vast array of data types to choose from. While primitive data types like integers and booleans are essential, they aren't always sufficient for complex applications. That's where non-primitive data types come in. In this article, we'll explore what non primitive data types in java are, how they differ from primitive types, and how to use them in Java.

non primitive data types in java

Data Types in Java

In Java, data types define the type and range of values that a variable can hold. They are used to specify the type of data that a variable can store, and they determine the operations that can be performed on that data. Java has strict type checking, which means you need to ensure that you use the correct data type for your variables and perform appropriate type conversions.

Data types in Java can be categorised into the following two categories:

  1. Primitive Data Types in Java: Primitive data types are used to represent basic data types. The primitive data types include int, short byte, long, float, double, char and boolean.
     
  2. Non Primitive Data Types in Java: Non-primitive data types are also known as user-defined data types. These data types can be created or modified by users very easily. They are capable of storing multiple values. Additionally, we can invoke methods on non-primitive data types to execute specific operations. Examples include Classes, Strings, Arrays, Interface, Enums, Collections and Maps.

    Now, we will discuss Non Primitive Data Types in Java in complete detail.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What are Non-Primitive Data Types?

Non Primitive data types in Java include - Arrays, Classes, Strings, and Interfaces. They are also known as reference types because they hold references to objects in memory rather than actual values. This contrasts with primitive data types, such as integers or booleans, which hold actual values. 

When you declare a variable of a non-primitive type, such as a String or an ArrayList, you create a reference to an object in memory. For example, in the syntax given below, you are declaring a String variable and assigning it a value.

 

Syntax

String myString = "Hello, world!";

 

In the above example, you are creating a String object that stores reference to a location in memory that contains the value "Hello, World!". When you pass a non-primitive data type to a method or assign it to another variable, you are passing the reference to the object rather than the object itself. Any changes made to the object through one reference will be reflected in all other references that point to the same object.

Referential v/s Non referential data types in Java

Types Of Non-Primitive Data Types in Java 

There exists four types of non primitive data types in Java. 

  1. Class
  2. String
  3. Array
  4. Interface
     

Now, let us discuss all four of them one by one in detail.

1. Class

A class is a blueprint or a defined template for creating objects. It contains data members (fields) and methods that define the behaviour of the objects created from it. The syntax for defining a class in Java is as follows:

Syntax:

public class ClassName 
{
	// Fields (data members)
	// Constructors
	// Methods
}

 

An object is an instance of the class. It is created using the new operator and stored in memory, occupying a specific location with its data members and methods. A Java class has following characteristics:

  • Class Name: A class name is a name given to a user-defined data type that serves as a blueprint for creating objects. Class names in Java follow the standard Java naming conventions.
     
  • Fields: Fields are the variables that define the state of an object. They can be of any data type, including primitive types, reference types or arrays. Fields can be publicprivate, or protected, depending on their visibility and accessibility.
     
  • Constructors: Constructors are special methods that are used to initialize the state of an object when it is created. Constructors have the same name as the class and can be overloaded to provide different ways of creating objects.
     
  • Methods: Methods are the functions that define the behaviour of an object. Methods can take parameters as input. They can be of any return type, including the void return type. Methods can be public, private, or protected, depending on their visibility and accessibility.
     
  • Access Modifier: While declaring a class, we can make it public, private or protected by using the public, private or protected keyword. When there is no access modifier specified, then the class is assumed to have a default access.
Class in Java

Example

We have a class with the name Calculator outside the public Main class. It consists of methods addNumbers and subNumbers with parameters to perform addition and subtraction operations. It also contains a default constructor that will get invoked automatically upon creating an object and will print what is fed to it.

Code

class Employee 
{
    // Variables of class
    int employeeID;
    String employeeName;
    
    // Making a default constructor, it assigns name and ID of employee
    Employee(int ID, String Name)  
    {
        employeeID = ID;
        employeeName = Name;
        System.out.println("Name of employee is " + employeeName + " ans ID is " + employeeID);
    }
    
    // Member function of class, it changes name of the employee
    void changeName(String Name)
    {
        employeeName = Name;
        System.out.println("Changed name of employee is " + employeeName);
    }
    
}


public class Main
{
	public static void main(String[] args) 
	{
		emp = new Employee(7379, "Elisha"); // making an instance of employee class
 		emp.changeName("Maria"); //calling the method 
	}
}


Output:

Name of employee is Elisha and ID is 7379
Changed name of employee is Maria

2. Interface

Interfaces in Java are a collection of abstract methods (methods without a body) defining a set of behaviours a class can implement. An interface serves as a contract between two classes, i.e. the interface defines what methods a class must implement, but it does not specify how those methods should be implemented. Interfaces in Java can contain Abstract MethodsDefault and Static Methods or Private Methods.

To implement an interface, a class must use the implements keyword followed by the interface's name. It's compulsory for a class to provide an implementation for all the interface's methods. A particular interface can be implemented by any number of classes.

Example

In the Java code below, we have implemented an interface consisting of two abstract methods: int CalculateDiscount() and void WelcomeNote(), without defining them. Now, they have to be implemented by the class GoldShop, where we will implement both methods. After that, we have made an object of GoldShop class and using this, we will invoke WelcomeNote() and CalculateDiscount() methods. In the end, the result will be displayed as output.

Code

interface JwelleryShop 
{
    // Methods without definition
    void WelcomeNote();
    int CalculateDiscount();
}


class GoldShop implements JwelleryShop 
{
    // GoldShop class implements the JwelleryShop interface
    String ShopName;
    int Discount;
    
    // implementing the constructor
    GoldShop(String A, int B)
    {
        ShopName = A;
        Discount = B;
    }
    
    // implementing the interface methods
    public void WelcomeNote()
    {
        System.out.println("Welcome to our shop " + ShopName);
    }
    
    public int CalculateDiscount() 
    {
        return Discount;
    }
}

public class Main 
{
    public static void main(String[] args)
    {
        GoldShop shop = new GoldShop("ABC Jewels", 5); // Making instance of GoldShop
        
        shop.WelcomeNote(); //calling method
        
        int netDiscount = shop.CalculateDiscount(); //calling method
        System.out.println(netDiscount);


    }
}

 

Output:

Welcome to our shop ABC Jewels.
2

3. Array

Arrays are used to store elements of the same data type, which are placed in a contiguous manner in memory. This means that the elements of an array are stored one after the other, with no gaps or spaces in between. This allows for efficient access to the elements of the array, as they can be accessed directly based on their index.

Each array has a unique reference name, which is used to access all its elements. This reference name is similar to a variable name used to identify and manipulate the array in the program. 

Example:

In Java, arrays are declared using the following syntax:

Syntax

// Declaration of array
<data_type>[] <array_name> = new <data_type>[size];
// Declaration and Initialization of array at the same time
<data_type> <array_name> [] = {array_items};

 

Actual Implementation : 

int[] arr = new int[5];
int arr[] = {1,2,3,4,5};
Arrays in Java

The following points should be kept in mind regarding arrays in Java:

  • Arrays in Java have a fixed size, which means that once an array is created, its size cannot be changed.
  • One important characteristic of arrays in Java is that they are dynamically allocated. This means that the memory space for the array is allocated at runtime, when the program is executed, rather than at compile time, when the code is compiled.

4. String

A string is an object representing a sequence of characters. Java provides a built-in class called String for working with strings. String literals are enclosed in double quotes, for example: "Non Primitive Data Types in Java". Strings are immutable, meaning that once a string object is created, its contents cannot be changed.

Strings are widely used in Java programs for various purposes, such as user input, file processing, and network communication. They are an important data type in Java and are supported by many programming constructs and APIs. The syntax for declaring a String is as follows:

Syntax

String <variable_name_of_string> = “<your_string>”;

OR

String <variable_name_of_string> = new String(“<your_string>”);

 

Actual Implementation:

//String Declaration in Standard way
String myString = "Hello, world!";
//String Declaration using new keyword
String myString = new String("Hello, world!");

Frequently Asked Questions

What are the non-primitive data types?

In Java, a non-primitive data type is a data type that is not one of the built-in primitive types such as int, char, boolean, etc. You can create non-primitive data types using classes or interfaces in Java.

What data types are primitive in Java?

Primitive data types have a fixed size in memory and represent basic building blocks for storing simple values. Some examples of primitive data types in Java are int, float, short, double, boolean, char, etc. 

How many non-primitive types are there in Java?

There are 4 non-primitive data types in Java - String, Array, Class, and Interface. They are also called reference data types and are used to create objects and provide an abstraction over complex data structures.

Which are three types of primitive data used in Java?

The 3 primitive data types in Java are numeric(int, float, double, etc.), textual(byte, char), and boolean data types. These can only contain simple values, and they come with a number of operations predefined.

Conclusion

We hope you got a fair idea about non primitive data types in Java. In conclusion, non primitive data types in Java are essential for programming complex applications that require more sophisticated Data Structure. Non-Primitive data types in Java are classified as Class, Array, String, and Interface.

To learn more about Data Structures and Algorithms, you can enroll in our course on DSA in Java.

Happy Coding!

Previous article
Finalize() Method in Java
Next article
HashCode() Method in Java
Live masterclass