The Wayback Machine - http://web.archive.org/web/20240910072937/https://www.geeksforgeeks.org/string-initialization-java-string-literal-vs-string-object/
Open In App

String Literal Vs String Object in Java

Last Updated : 23 Jan, 2018
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Compare string initialization performance for String Literal and String object.
String Literal

String str = “GeeksForGeeks”;

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 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 performance of string literal and string object, string object will always take more time to execute than 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.




// 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 taken to execute string literal = 0
Time taken to execute string object = 2


Similar Reads

Spring - Injecting Literal Values By Setter Injection
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML)
4 min read
Spring - How to Load Literal Values From Properties File
Literals in Java are a synthetic representation of boolean, numeric, character, or string data. It is a medium of expressing particular values in the program, such as an integer variable named ‘’/count is assigned an integer value in the following statement. int x = 100; // Here 100 is a constant/literal. Illustration: String literal. String s = "H
5 min read
Spring - Injecting Literal Values By Constructor Injection
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML)
5 min read
Collator compare(Object, Object) method in Java with Example
The compare() method of java.text.Collator class is used to compare the strength of two objects and it will return 0, positive and negative value as an output according to the result . Syntax: public int compare(Object o1, Object o2) Parameter: This method takes two objects between which comparison is going to take place.Return Value: if the first
2 min read
Convert Java Object to Json String using Jackson API
JSON stands for JavaScript Object Notation. It's a standard text-based format that shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. In order to convert a Java object into JSON, the following two me
3 min read
PrintWriter printf(Locale, String, Object) method in Java with Examples
The printf(Locale, String, Object) method of PrintWriter Class in Java is used to print a formatted string in the stream using the given Locale. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintWriter printf(Locale locale, String format, Object...args) Parameters: This method accepts two mand
2 min read
PrintWriter printf(String, Object) method in Java with Examples
The printf(String, Object) method of PrintWriter Class in Java is used to print a formatted string in the stream. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintWriter printf(String format, Object...args) Parameters: This method accepts two mandatory parameter: format which is the format ac
2 min read
PrintWriter format(String, Object) method in Java with Examples
The format(String, Object) method of PrintWriter Class in Java is used to print a formatted string in the stream. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintWriter format(String format, Object...args) Parameters: This method accepts two mandatory parameter: format which is the format ac
2 min read
PrintStream printf(String, Object) method in Java with Examples
The printf(String, Object) method of PrintStream Class in Java is used to print a formatted string in the stream. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintStream printf(String format, Object...args) Parameters: This method accepts two mandatory parameter: format which is the format ac
2 min read
PrintWriter format(Locale, String, Object) method in Java with Examples
The format(Locale, String, Object) method of PrintWriter Class in Java is used to print a formatted string in the stream using the given Locale. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintWriter format(Locale locale, String format, Object...args) Parameters: This method accepts two mand
2 min read
PrintStream format(Locale, String, Object) method in Java with Examples
The format(Locale, String, Object) method of PrintStream Class in Java is used to print a formatted string in the stream using the given Locale. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintStream format(Locale locale, String format, Object...args) Parameters: This method accepts two mand
2 min read
PrintStream printf(Locale, String, Object) method in Java with Examples
The printf(Locale, String, Object) method of PrintStream Class in Java is used to print a formatted string in the stream using the given Locale. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintStream printf(Locale locale, String format, Object...args) Parameters: This method accepts two mand
2 min read
PrintStream format(String, Object) method in Java with Examples
The format(String, Object) method of PrintStream Class in Java is used to print a formatted string in the stream. The string is formatted using specified format and arguments passed as the parameter. Syntax: public PrintStream format(String format, Object...args) Parameters: This method accepts two mandatory parameter: format which is the format ac
2 min read
Convert Java Object to Json String using GSON
JSON Stand for JavaScript Object Notation. It's a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To convert a Java object into JSON, the following methods can be
2 min read
Convert Json String to Java Object Using GSON
Pre-requisite: Convert Java Object to Json String Using GSONJSON Stand for JavaScript Object Notation. It's a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To co
3 min read
Console printf(String, Object) method in Java with Examples
The printf(String, Object) method of Console class in Java is used to write a formatted string to the output stream of the console. It uses the specified format string and arguments. It is a convenience method. Syntax: public Console printf(String fmt, Object... args) Parameters: This method accepts two parameters: fmt - It represents the format of
2 min read
Console format(String, Object) method in Java with Examples
The format(String, Object) method of Console class in Java is used to write a formatted string to the output stream of the console. It uses the specified format string and arguments. Syntax: public Console format(String fmt, Object... args) Parameters: This method accepts two parameters: fmt - It represents the format of the string. args - It repre
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
List remove(Object obj) method in Java with Examples
The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List. Syntax: boolean remove(Object obj) Parameters: It accepts a single parameter obj of List type which represents the element to be removed from the given List. Return Value: It return
2 min read
ZoneOffset equal(Object) method in Java with Examples
The equals(Object) method of ZoneOffset Class in java.time package is used to check whether the another instance of ZoneOffset passed as the parameter to this ZoneOffset instance, is equal or not. This method returns a boolean value stating the same. Syntax: public boolean equals(Object object) Parameters: This method accepts a parameter object whi
2 min read
Stack indexOf(Object, int) method in Java with Example
The Java.util.Stack.indexOf(Object element, int index) method is used to the index of the first occurrence of the specified element in this Stack, searching forwards from index, or returns -1 if the element is not found. More formally, returns the lowest index i such that (i &gt;= index &amp;&amp; Objects.equals(o, get(i))), or -1 if there is no su
2 min read
Stack add(Object) method in Java with Example
The add(Object) method of Stack Class appends the specified element to the end of this Stack. Syntax: boolean add(Object element) Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended to end of the Stack. Return Value: This method returns True after successful
2 min read
Stack add(int, Object) method in Java with Example
The add(int, Object) method of Stack Class inserts an element at a specified index in the Stack. It shifts the element currently at that position (if any) and any subsequent elements to the right (will change their indices by adding one). Syntax: void add(int index, Object element) Parameters: This method accepts two parameters as described below.
2 min read
Stack remove(Object) method in Java with Example
The Java.util.Stack.remove(Object o) method is used to remove any particular element from the Stack. Syntax: Stack.remove(Object o) Parameters: This method accepts a mandatory parameter o is of the object type of Stack and specifies the element to be removed from the Stack. Return Value: Returns True if the specified element is found and removed fr
2 min read
Stack lastIndexOf(Object, int) method in Java with Example
The Java.util.Stack.lastIndexOf(Object element, int last_index) method is used to the last index of the first occurrence of the specified element in this Stack, searching forwards from last index, or returns -1 if the element is not found. More formally, returns the lowest last index i such that (i &gt;= last index &amp;&amp; Objects.equals(o, get(
3 min read
AbstractSequentialList set(int, Object) method in Java with Example
The set() method of Java AbstractSequentialList is used to replace any particular element in the list created using the AbstractSequentialList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method. Syntax: public E set(int index, Object element)
3 min read
PrintWriter println(Object) method in Java with Examples
The println(Object) method of PrintWriter Class in Java is used to print the specified Object on the stream and then break the line. This Object is taken as a parameter. Syntax: public void println(Object object) Parameters: This method accepts a mandatory parameter object which is the Object to be printed in the Stream. Return Value: This method d
2 min read
PrintWriter print(Object) method in Java with Examples
The print(Object) method of PrintWriter Class in Java is used to print the specified Object on the stream. This Object is taken as a parameter. Syntax: public void print(Object object) Parameters: This method accepts a mandatory parameter object which is the Object to be printed in the Stream. Return Value: This method do not returns any value. Bel
2 min read
PrintStream print(Object) method in Java with Examples
The print(Object) method of PrintStream Class in Java is used to print the specified Object on the stream. This Object is taken as a parameter. Syntax: public void print(Object object) Parameters: This method accepts a mandatory parameter object which is the Object to be printed in the Stream. Return Value: This method do not returns any value. Bel
2 min read
PrintStream println(Object) method in Java with Examples
The println(Object) method of PrintStream Class in Java is used to print the specified Object on the stream and then break the line. This Object is taken as a parameter. Syntax: public void println(Object object) Parameters: This method accepts a mandatory parameter object which is the Object to be printed in the Stream. Return Value: This method d
2 min read
Article Tags :
Practice Tags :