Is String a primitive data type or an object in Java?


String is not a primitive data type. Java.lang package provides the String class therefore, it is an object type. You can create a string variable directly like any other variables as −

String s = "myString";

(or)

By instantiating the string class using the new keyword as −

String s = new String("myString");

Example

 Live Demo

import java.util.Scanner;

public class StringExample {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sting value:");

String str = sc.nextLine();
System.out.println(str.getClass());
}
}

Output

Enter a sting value:
hello
class java.lang.String

Updated on: 30-Jul-2019

850 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements