Creating a Java String Object

Possible duplicate:
What is the purpose of the expression "new String (...)" in Java?

Hi,

1) What is the difference between the two statements:

String s1 = "abc";

and

String s1 = new String("abc")

2) since I am not using the new one in the first statement how the string object will be created

thank

+3
source share
2 answers

In the first case, the compiler knows the value of the string s1. Thus, all rows with the same value will use the same memory cells:

String s1 = "abc";
String s2 = "abc";

Although there are two references to String (s1 and s2), there is only one “abc” sequence in memory. An operator is newnot needed because the compiler is doing the job.

String. , String :

String s1 = "abc";
String s2 = new String("abc");

"abc" 1 , "abc" 2. 2 - String.

+3

, . , . , . .

, (, ..).

, :

String sentence = "Lorem ipsum dolor sit amet";
String word = sentence.substring(5);

( ). , , , , . :

word = new String(word);
+3

Source: https://habr.com/ru/post/1748116/


All Articles