Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Storage

 
Mohammed Niaz M.
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
--------------------------------------------
1.

String Str = "A";
String lStr = "A";

The Str n lStr are stored in the same Heap memory?

--------------------------------------------
2.
String Str = "A";
String lStr = new String("A");

The Str n lStr are Different means stored in different locations(Heap),
The new operator do the tricks here?

----------------------------------------------

3.

String Str = new String("A");
String lStr = new String("A");

These two strings are stored in same heap locations?

-------------------------------------------------------

Thanks in Advance.
 
Javier Corral
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String Str = "A";
String lStr = "A";

The Str n lStr are stored in the same Heap memory?

"A" is a literal String, then it will go to the String pool only once becouse the second literal is the same. If you try "if (Str == lStr)" you will get true. (It means that Str and lStr have the same reference to the String pool.)
--------------------------------------------


String Str = "A";
String lStr = new String("A");

The Str n lStr are Different means stored in different locations(Heap),
The new operator do the tricks here?

You have two "A" but, as before, it goes to the literal String pool only once. Str have a reference to the "A" in String pool. lStr have a reference to an object String created in somewhere in the heap. If you try "if (Str == lStr)" you will get now false (but if you try "Str.equals(lStr)" then true).
----------------------------------------------

String Str = new String("A");
String lStr = new String("A");

These two strings are stored in same heap locations?

These are new objects and different objects. Using new you are creating one new object every time. If you try "if (Str == lStr)" you will get false. (but the String pool still have one "A")(if you try "if (Str.equals(lStr))" you will get true).
-------------------------------------------------------
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic