What is the difference between string object and string literal

+1 vote
Feb 28, 2019 in Java by Phalguni
• 1,020 points
52,296 views

4 answers to this question.

+1 vote

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 which 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; i++)
        {
            String s1 = "Hello World";
            String s2 = "Welcome";
        }
                 long end1 = System.currentTimeMillis();
        long total_time = end1 - start1;
          System.out.println("Time taken to execute"+ 
                " string literal = " + total_time);
                long start2 = System.currentTimeMillis();
                 for (int i = 0; i < 10000; i++)
        {
            String s3 = new String("Hello World");
            String s4 = new String("Welcome ");
        }
              long end2 = System.currentTimeMillis();
        long total_time1 = end2 - start2;
          System.out.println("Time taken to execute"+
                   " string object=" + total_time1);
    }
}
answered Feb 28, 2019 by Avantika
• 1,520 points

edited Mar 15, 2019 by Kalgi
+3 votes

String literal is a Java language concept. This is a String literal:

"a String literal"

String object is an individual instance of the java.lang.String class.

String s1 = "abcde";
String s2 = new String("abcde");
String s3 = "abcde";

All are valid, but have a slight difference. s1 will refer to an interned String object. This means, that the character sequence "abcde" will be stored at a central place, and whenever the same literal "abcde" is used again, the JVM will not create a new String object but use the reference of the cached String.

s2 is guranteed to be a new String object, so in this case we have:

s1 == s2 // is false
s1 == s3 // is true
s1.equals(s2) // is true
answered Aug 16, 2019 by Sirajul
• 59,210 points
and if you do

String s1 = new String("abc");

String s2 = new String("abc");

System.out.println(s1==s2)

op:

false
+1 vote

When you use a string literal the string can be interned, but when you use a new String("...") you get a new string object. In general, you should use the string literal notation when possible. It is easier to read and it gives the compiler a chance to optimize your code.

answered Dec 15, 2020 by Gitika
• 65,890 points
+1 vote

String Literal

String str = “Edureka”;

This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value “GeeksForGeeks”, then str will reference of that string and no new String object will be created. Please refer Initialize and Compare Strings in Java for details.

String Object

String str = new String(“GeeksForGeeks”);

This is a string object. In this method, JVM is forced to create a new string reference, even if “GeeksForGeeks” is in the reference pool.

Therefore, if we compare the performance of string literal and string object, a string object will always take more time to execute than a string literal because it will construct a new string every time it is executed.
Note: Execution time is compiler dependent.

Below is the Java program to compare their performances.

filter_none

edit

play_arrow

brightness_4
// Java program to compare performance 

// of string literal and string object

  

class ComparePerformance {

  

    public static void main(String args[])

    {    

        // Initialization time for String

        // Literal

        long start1 = System.currentTimeMillis();

          

        for (int i = 0; i < 10000; i++)

        {

            String s1 = "GeeksForGeeks";

            String s2 = "Welcome";

        }

          

        long end1 = System.currentTimeMillis();

        long total_time = end1 - start1;

  

        System.out.println("Time taken to execute"+ 

                " string literal = " + total_time);

  

        // Initialization time for String

        // object

        long start2 = System.currentTimeMillis();

          

        for (int i = 0; i < 10000; i++)

        {

            String s3 = new String("GeeksForGeeks");

            String s4 = new String("Welcome");

        }

          

        long end2 = System.currentTimeMillis();

        long total_time1 = end2 - start2;

  

        System.out.println("Time taken to execute"+

                   " string object=" + total_time1);

    }

}

Output:

Time is taken to execute string literal = 0
Time taken to execute string object = 2

answered Dec 15, 2020 by Roshni
• 10,520 points

Related Questions In Java

0 votes
1 answer

What is the difference between main(String[] args) and main(String... args) in Java?

String[] is used to accept a single parameter ...READ MORE

answered Sep 6, 2019 in Java by Piya
2,822 views
0 votes
2 answers

What is the difference between implements and extends?

Extends : This is used to get attributes ...READ MORE

answered Aug 3, 2018 in Java by samarth295
• 2,220 points
10,650 views
0 votes
1 answer

What is the difference between jdk and jre?

JRE: It stands for Java Runtime Environment. ...READ MORE

answered Apr 20, 2018 in Java by Akrati
• 3,190 points
1,096 views
0 votes
2 answers

What is the difference between = and equals()?

The equals() method compares the "value" inside String instances ...READ MORE

answered Aug 13, 2018 in Java by Daisy
• 8,120 points
656 views
+5 votes
4 answers

How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

answered Mar 27, 2018 in Java by DragonLord999
• 8,450 points

edited Nov 7, 2018 by Omkar 69,264 views
+1 vote
1 answer

How to handle drop downs using Selenium WebDriver in Java

First, find an XPath which will return ...READ MORE

answered Mar 27, 2018 in Selenium by nsv999
• 5,500 points
7,152 views
0 votes
1 answer

What are the differences between getText() and getAttribute() functions in Selenium WebDriver?

See, both are used to retrieve something ...READ MORE

answered Apr 5, 2018 in Selenium by nsv999
• 5,500 points
15,312 views
0 votes
1 answer

Selenium JARS(Java) missing from downloadable link

Nothing to worry about here. In the ...READ MORE

answered Apr 5, 2018 in Selenium by nsv999
• 5,500 points
3,424 views
0 votes
2 answers

What is the difference between Set and List in java?

List is an ordered sequence of elements. ...READ MORE

answered Apr 26, 2018 in Java by Akrati
• 3,190 points
45,386 views
0 votes
2 answers

What is the difference between getAttribute() and getParameter() in java?

getParameter() returns http request parameters. Those passed from ...READ MORE

answered Aug 28, 2019 in Java by Sirajul
• 59,210 points
17,882 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP