×

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values).

These are not already built into the devices. These are created by the user based on the requirements of the user. Non-primitive data types are used for storing different values in a single variable. For example, an array can be used for storing multiple values. Hence these are called the advanced versions of storing values.

The memory address where the data is saved in heap memory, or the storage address where an object is created, is referenced whenever a non-primitive data type is created. A non-primitive data type variable also was known as an object reference variable or a referred data type.

An object reference variable lies on the stack memory, whereas the object it refers to resides in the secondary storage at all times. A reference to the object in a heap is stored in the stack.

All non-primitive data types in Java are referred to as "objects," and they are produced by creating a class.

Key points:

1. For storing any values, it assigns null as default.

2. Anytime we supply a non-primitive data type to a method, we also provide the address of the object containing the data.

Types of Non-primitive data types:

Non-primitive data types are classified into five types in java.

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

Class and Object:

Class is a data type in java created by the user; hence it is called a user-defined data type. It is used as a template for the member variables and methods-based data.

An Object is an instance of the class that can be used for accessing the class elements and methods.

The below example will describe the methods and variables for creating the class. In the example, a class is created which consists of methods( addition( ) and subtraction( ) ). These methods can be accessed from the class by using the object ob.

Datatypes.java

class Datatypes {  
       // declaring the variables of the class Datatypes 
        int num1 = 20;  
        int num2 = 10;  
        int num3;    
        // the methods of Datatypes class  
        public void addition() {  
            int num3 = num1  + num2;  
            System.out.println("The sum of the two numbers is: " + num3);  
        }  
        public void subtraction() {  
            int num3 = num1 - num2;  
            System.out.println("The difference between two numbers: " + num3);  
        }  
    // main section  
    public static void main (String[] args) {  
        // object ob is created
        Datatypes ob = new Datatypes();    
        //calling the methods of Datatypes class  
        ob.addition();  
        ob.subtraction();  
    }  
}  

Output:

Interface

Interface and class are similar, but the interface consists of only abstract methods, while a class contains different methods.

Note: If a particular class implements the interface, then all the interface methods should be implemented. Else we can declare it as abstract.

An Interface Calculate is created in the below example, consisting of two abstract methods in the Interface( add( ) and multiply( ) ). The class Example implements the interface, and the interface's methods can be accessed by creating the objects in the Example class.

Example.java

interface Calculate {  
    void add();  
    void multiply();  
}  
public class Example implements Calculate {  
      
        // defining the variables of class  
        int num1 = 10;  
        int num2 = 20;  
        int num3;  
  
        // the methods of the interface are implemented  
        public void multiply() {  
            int num3 = num2 * num1;  
            System.out.println("The product of two numbers: " + num3);  
        }  
        public void add() {  
            int num3 = num2 + num1;  
            System.out.println("The sum of two numbers is: " + num3);  
        }  
    // main section 
    public static void main (String[] args) throws IOException {  
        Example obj = new Example();  
        // calling the methods using the interface  
        obj.multiply();  
        obj.add();  
    }  
}  

Output:

Non-primitive data types in Java

String

A string is a group of characters, such as “ Java”, ” Programming”, etc. In java, the string is defined as the class and datatype. Example for string creation in java:

String str= " Java";

Example 1

StringEx.java

public class StringEx {  
    public static void main(String[] args) {  
          
        // a String Str is created and initialised it 
        String str = "Welcome! An Example of string";  
          
        // substring method is used  
        String subString = str.subString(0,14);  
  
        // result of substring  
        System.out.println(subString);  
    }  
} 

Example 2

Palindrome.java

public class Palindrome{


public static void main(String[] args) {

isPalindrome("abc");
isPalindrome("abcba");
isPalindrome("Non-primitive data types in Java");
}


private static void isPalindrome(String input) {
boolean res = true;
int len = input.length();
for(int j=0; j < length/2; i++) {
if(input.charAt(i) != input.charAt(length-i-1)) {
res= false;
break;
}
}
System.out.println(input + " is palindrome = "+res);

}
}

Output:

Non-primitive data types in Java

Array

A data type called an array allows for the sequential storage of many homogeneous variables or variables of the same type. They are kept in an indexed format with index zero. The data types of the elements can be either primitive or non-primitive.

Declaring an array with the primitive datatype int:

int age [ ];

The example below describes the initialisation of the array and how to retrieve the array elements using the for a loop.

ArrayEx.java

import java.io. * ;  
import java.util. * ;  
public class ArrayEx {  
  public static void main(String[] args) throws IOException {  
    int i;  
    Scanner sc = new Scanner(System. in );  
    // array was declared, and it was initialised  
    int array[] = {1, 2, 3, 4, 5};  
    // Another array array1 is declared 
    int array1[] = new int[5];  
    // user is requested to enter the values  
    System.out.println("Put the numbers (size = 5) :");  
    for (i = 0; i < 5; i++) {  
      array1[i] = sc.nextInt();  
    }  
    System.out.println("Previous array with initialized size is: ");  
    for (i = 0; i < 5; i++) {  
      System.out.print(array[i] + " ");  
    }  
    System.out.println("\nDynamically the user entered:");  
    for (i = 0; i < 5; i++) {  
      System.out.print(array1[i] + " ");  
    }  
  }
}

Output:

Non-primitive data types in Java

Related Topics

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

How to find length of integer in Java

We can find the length of the integer in many ways. The length of an integer is defined as the count of the number of digits for the given integer. These...

5 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.