-2

Consider the following code.

String s = "Hello"; 
s = "Good Bye";
s = "Hello";

I understand the first two lines of the code allocates RAM for the String objects "Hello" and "Good Bye". However, does the third line create a third RAM location for another "Hello" or does s refer back to the location of the first "Hello"?

HK boy
  • 1,398
  • 11
  • 17
  • 25
  • [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) – Abra Dec 05 '19 at 03:04
  • @maytham-ɯɐɥʇʎɐɯ That's wrong, `s` refers to the same object after the first line of code and after the 3rd line of code, since both `"Hello"` strings refer to the same object instantiated from the class' constant pool. – Erwin Bolwidt Dec 05 '19 at 03:07

2 Answers2

-1

The memory for an immutable string is statically allocated. When "s" is assigned to a different value, the previous reference is removed, and the "s" now points to a new location. All the strings are stored in the compiled byte code file. Garbage collector is not even involved in this case. It's up to the compiler to recognize that the first and second Hello are the same. You can use a string grabber to see how many Hello's are present in the byte code binary.

Ian Heisler
  • 111
  • 6
-1

yes,just google java memory model. if s=new String("Hello"); s refer to annother location