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
|
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
|
Character at index 1 is - n