We know that there are two ways to create a String variable:

String str1 = "abcd";
String str2 = new String("abcd");
Copy the code

So why do these two types of creation exist, and what are the differences between their representations in memory?

Here are two common interview questions.

Interview Question 1:
String a = "abcd";
String b = "abcd";
System.out.println(a == b);  // true
System.out.println(a.equals(b)); // true
Copy the code

Resolution:

== and equals return true. This is because a and B refer to the same string in the method area. Therefore, the same string is created only once in the method area when it is created repeatedly.

Interview Question 2:
String c = new String("abcd");
String d = new String("abcd");
System.out.println(c == d);  // false
System.out.println(c.equals(d)); // true
Copy the code

Resolution:

Equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals Strings created with new are created in the JVM heap each time, so c and D correspond to two different strings in the heap.

The string created by “and new” in these two problems can be seen in the following figure.

Recommended reading

Dry goods: Free 2TB architect four-stage video tutorial

Interview: the most complete Java multithreaded interview questions and answers

Tools: Recommended an online creation flow chart, mind mapping software

Share Java dry goods, high concurrency programming, hot technology tutorials, microservices and distributed technology, architecture design, blockchain technology, artificial intelligence, big data, Java interview questions, and cutting-edge hot news.