Mixing Java strings of immutable strings

If Stringimmutable in Java, then how can we write like:

String s = new String();
s = s + "abc";
+5
source share
8 answers

Your string variable is NOT a string. This is the LINK for the String instance.

See for yourself:

String str = "Test String";
System.out.println( System.identityHashCode(str) ); // INSTANCE ID of the string

str = str + "Another value";
System.out.println( System.identityHashCode(str) ); // Whoa, it a different string!

The instances that the str variable indicates are individually immutable, BUT the variable can be pointed to any String instance that you want.

If you do not want str to be reassigned to point to another instance of the string, declare it final:

final String str = "Test String";
System.out.println( System.identityHashCode(str) ); // INSTANCE ID of the string

str = str + "Another value"; // BREAKS HORRIBLY
+7
source

Lines are immutable. This means that the instance Stringcannot change.

s, ( ) String.

+8

. .

s = s+"abc" s. , s ( ) "abc".

. , append() , StringBuilder StringBuffer.

Java .

+2

- , , :

Foo f = new Foo("a");
f.setField("b"); // Now, you are changing the field of class Foo

, . String, , , , . :

String s = "Hello";
s.substring(0,1); // s is still "Hello"
s = s.substring(0,1); // s is now referring to another object whose value is "H"
+1
   String s = new String();  

, , , "s" .

   s = s+"abc";              

, ; "abc", "s" .

0

, , s = s + "abc"; , String ( s "abc" ), String s. , s .

, . , , .

0
String s = new String();

String (""). s .

s = s + "abc";

"abc" - ( , String, ), ( , , ). new String(), , , . -, .

, s + "abc", ("") "abc" String, "abc", , , , s "abc" .

0

, , , , !

, Java, , (, ), , . ( .)

, , String , String . , , . , , "" ( ). , , StringBuffer, . (, StringBuffer, .) StringBuffers , , (a) , Java , , (b) .

I hope this helps people who read this topic and try to learn!

-2
source

All Articles