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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 10-Jan-2018 06:07:18
Advertisements