What is the difference between string object and string literal

732    Asked by SakshiD’souza in Java , Asked on Jul 28, 2021

not available

Answered by Abhishek Shukla

Difference between string objects and string literals

A string literal in Java is basically a sequence of characters from the source character set used by Java programmers to populate string objects or to display text to a user. These characters could be anything like letters, numbers or symbols which are enclosed within two quotation marks.

A string object is one which lets you work with a series of characters. It basically wraps all Javascript’s string primitive data type with a number of helper methods. The main function of JavaScript is it automatically converts between string primitives and string objects.

The main difference between String objects and string literals is mentioned below:

  • String Objects
  • String Literals

A new keyword is used to create an object and the object is created in the heap memory whereas its reference will be pointed to String pool.

Here the reference will be directly referred to String Pool. JVM initially checks for the availability with the same value in the constant pool

Here is an illustration of a Java Program that compares their performances.

class ComparePerformance {
      public static void main(String args[])
    {
        long start1 = System.currentTimeMillis();
                  for (int i = 0; i < 10000 s1 = "Hello World" s2 = "Welcome" xss=removed xss=removed literal = " + total_time);
                long start2 = System.currentTimeMillis();
                 for (int i = 0; i < 10000; i++)
        {
            String s3 = new String(" xss=removed xss=removed xss=removed xss=removed>
<br>

Your Answer

Interviews

Parent Categories