Two methods and differences of string definition in java

Two methods and differences of String definition in java

The first; new method
String s1 = new String("hello world");
String s2 = new String("hello world");
System.out.println(s1 == s2);//output false

The second:
String s3 = "hello world";
String s4 = "hello world";
System.out.println(s3 == s4);//output true

The java program above first creates a buffer with the string "hello world" in it.
In the second method, when creating a new string, it will first check whether the buffer has the string, and if so, return it directly for reference without creating a buffer. So, the output result is true.
In the first method, it will also check whether the string exists in the buffer, but whether there is or not, a new heap will be created. If the string does not exist in the buffer, a new one will be created. I thought it was two heaps, so the two strings were different, and the output was false.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325605885&siteId=291194637