Tuesday, November 19, 2024
Google search engine
HomeData Modelling & AIIs String a Primitive or a Derived Type?

Is String a Primitive or a Derived Type?

In this article, we are going to discuss whether String is a primitive data type or a Derived data type.

Definitely, String is not a primitive data type. It is a derived data type. Derived data types are also called reference types because they refer to an object. They call methods to perform operations. A string is a Class present in Java.lang package. A string can be created directly by assigning the set of characters enclosed in double-quotes to a variable or by instantiating a String class using the new keyword. Let’s look into a few examples of String initialization/declaration.

String str1 = “Geeks_for_Geeks”; // direct way

String str2 = new String(“GFG”); // instantiating String class using the new keyword

Let’s look into the sample examples on Strings in Java.

Example 1: Here in the below code a String is initialized and declared in the normal way (just like we used to do in the case of primitive types) and called a method getClass() which specifies the Class where the String is present.

Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        // normal way of string initialization and
        // declaration
        String s1 = "GFG";
        System.out.println(s1 + "\n" + s1.getClass());
    }
}


Output

GFG
class java.lang.String

Example 2: As String is a Derived type it is capable of calling various methods. Here in this code, we called a charAt() method which accepts an Integer as index position and returns a character at that specified index.

Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        String str = new String("India");
        // returns character at index 1
        System.out.println("Character at index 1 is - "
                           + str.charAt(1));
    }
}


Output

Character at index 1 is - n

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments