0

i know Strings are immutable in java and i just read some theory about it Once a String is declared it cannot be changed . i declared a String and changed it's value just by appending some value to it . it should not have happened

   String s = "amol";
   s = s + "abc";
   System.out.println(s); //output is amolabc
Amol
  • 303
  • 4
  • 13

4 Answers4

1

The String s didn't get changed. When you did s + "abc", it created a new String object with the result of the operation.

MujjinGun
  • 480
  • 3
  • 9
0

You need to understand the concept of String Pool in Java. Please go through the link http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html

0

You are right that Strings are immutable. Here, You didn't change the String s. All distinct Strings are stored in the Heap Memory. So, all the variables (say 10 variables ) containing the same String (say "Hello" ) will occupy only 5 bytes of memory. They all will point to the same location. Separate instances will not be stored for each of those variables. Here, when you write s = s + "abc", a new string "amolabc" is created in the heap,and now the variable s just points to the new string in the heap. You didn't modify the value of "amol". You just made a new String.

Dhumil Agarwal
  • 856
  • 2
  • 11
  • 19
0

The meaning of immutable is not like you thought to be.Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used.

here you are appending another string value to it,which can be done.But you cannot concatenate with another string.

By appending it is creating another string.

Refer here

VVN
  • 1,607
  • 2
  • 16
  • 25