Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How string literals are created?

Tags:

java

string

I am trying to understand the string constant pool, how string literal objects are managed in constant pool, i am not able to understand why I am getting false from below code where s2 == s4

 public static void main(String[] args) {
    String s1 = "abc";
    String s2 = "abcd";
    String s3 = "abc" +"d";
    String s4 = s1 + "d";
    System.out.println(s2 == s3); //  OP:  true
    System.out.println(s2 == s4); // OP:  false
 }
like image 838
Satya Avatar asked May 22 '13 12:05

Satya


People also ask

How are string literals created in Java?

Java String literal is created by using double quotes.

Are string literals created from stack?

In Java, strings are stored in the heap area. Why Java strings stored in Heap, not in Stack? String Literal is created by using a double quote.

How are string literals stored?

The characters of a literal string are stored in order at contiguous memory locations. An escape sequence (such as \\ or \") within a string literal counts as a single character.

How many objects are created in string literal?

The answer is: 2 String objects are created. str and str2 both refer to the same object.


1 Answers

The expression "abc" + "d" is a constant expression, so the concatenation is performed at compile-time, leading to code equivalent to:

String s1 = "abc";
String s2 = "abcd";
String s3 = "abcd";
String s4 = s1 + "d";

The expression s1 + "d" is not a constant expression, and is therefore performed at execution time, creating a new string object. Therefore although s2 and s3 refer to the same string object (due to constant string interning), s2 and s4 refer to different (but equal) string objects.

See section 15.28 of the JLS for more details about constant expressions.

like image 108
Jon Skeet Avatar answered Sep 23 '22 19:09

Jon Skeet