What is the difference between string object and string in Java?

Asked 2 years ago, Updated 2 years ago, 113 views

String str = new String("abc"); Wow String str = "abc"; What's the difference?

string java string-literals

2022-09-22 22:20

2 Answers

Writing a String string refers to that string. However, the new String ("~~") is to create a new string object.

For example,

String a = "abc"; 
String b = "abc";
System.out.println(a == b);  // true

where a and b strings are the same object.

String c = new String("abc");
String d = new String("abc");
System.out.println(c == d);  // false

where c and d refer to different objects. If possible, we recommend that you use the String string. It's easier to read and gives the compiler the opportunity to optimize code.


2022-09-22 22:20

First of all, we need to understand Heap and the String constant pool that exists in it.

String a = new String("abc"); The above sentence creates a general object in heap and then has a ref of the object.

String b = "abc"; I understand that the above sentence is stored in the String constant pool in the heap, or if it is a string that already exists, it points to the index number of the stored array.

So, the result for a == b is false. Because it's not referring to the same object.

But a.This is true because equals(b) is the result of comparing the string itself.


2022-09-22 22:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.