Skip to content
Related Articles
Open in App
Not now

Related Articles

Is String a Primitive or a Derived Type?

Improve Article
Save Article
  • Last Updated : 28 Jun, 2022
Improve Article
Save Article

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!