Interview: what happens in memory when i initialize String str=”abc”; String str1=”abc”; String str=”xyz”

StackOverflow https://stackoverflow.com/questions/23534209

  •  17-07-2023
  •  | 
  •  

Question

Recently i attended an interview there they asked this question which i was unable to answer.

what happens in memory when i initialize

String str = "abc"; 
String str1 = "abc"; 
String str = "xyz";
Was it helpful?

Solution

Think it as Like this,

  1. When first Variable Str is initialized with "abc" then Literal "abc" gets memory in String Pool so variable Str gets reference to this "abc".

    Str --------------------------------> abc

  2. On Second Step, in similar fashion another variable reference to same literal in String Pool .

    Str --------------------------------> abc <------------------------------- Str1

  3. In final Step , if considered String Str then an Error will occur like this:-

    variable Str is already defined

    So instead i will take Str = "xyz" on doing this a New literal will get memory in String Pool and Str previous reference will be deleted and new reference will be assigned.

    Str -----------X-------------> abc <----------------------- Str1

    Str --------------------------> xyz

  4. Finally we will get this and will have 2 Literals namely abc and xyz in String Pool

    Str --------------------------> xyz and Str1 --------------------------> abc

OTHER TIPS

Assuming the third variable should have a different name:

At compile time, the identical "abc" strings will both be pulled into the string pool, along with the "xyz". So you'll end up with two String variables pointing to the same instance of "abc" and one pointing to "xyz".

A string object will be created in String constant pool(SCP) with content

 "abc"

1.str refernce will be pointed to that object.

While creating second object jvm will check whether the same "abc" content available in SCP or not in your case already available so

2 str1 will be pointed to existing object

3.String str="xyz" already str is pointing to abc content object again we are assigning to xyz

Code will not compile as you are using duplicate `str` variable 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top