What is difference between creating String as new and literal?

Category : Java | Sub Category : Java Interview questions | By Prasad Bonam Last updated: 2023-08-14 17:39:30 Viewed : 48

In programming, when creating strings, there is a difference between creating them using the new keyword and using string literals. The difference lies in how memory is allocated and how the strings are treated by the programming language.

Creating a String Using the new Keyword: When you create a string using the new keyword, you are explicitly creating a new instance of a string object in memory. This can be seen in languages like Java or C#. For example:

String str = new String("Hello");

In this case, a new memory location is allocated to store the string "Hello", and the reference str points to that location. Even if another string with the same content is created, it will occupy a different memory space.

Creating a String Using String Literals: String literals are sequences of characters enclosed in quotes. In many programming languages, including Java and C#, string literals are automatically pooled to optimize memory usage. This means that if you create multiple strings with the same content using string literals, they might share the same memory location. For example:

String str1 = "Hello"; String str2 = "Hello";

In this case, both str1 and str2 point to the same memory location where the string "Hello" is stored. This string pooling behavior can help reduce memory consumption when you have many identical string literals.

Key Differences:

  1. Memory Allocation: When using the new keyword, a new memory allocation is created for each instance, whereas string literals can share the same memory location due to string pooling.

  2. Mutability: In some programming languages, strings created using the new keyword might be mutable (modifiable), meaning you can change their content. String literals are often immutable (cannot be changed once created).

  3. Optimization: Using string literals with string pooling can optimize memory usage by reusing memory locations for identical strings.

  4. Coding Style: Using string literals is more common and idiomatic, as it is simpler and often more efficient due to string pooling.

  5. Garbage Collection: Strings created using the new keyword might need to be explicitly managed by garbage collection. String literals with pooling might be automatically managed by the language runtime.

In many cases, using string literals is preferred because of their simplicity, better memory optimization, and often improved performance due to pooling. However, there might be situations where using the new keyword for creating strings is necessary, especially when you need distinct instances or require mutable strings.

Related Articles

Leave a Comment: