Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Storage Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Storage" Watch "Storage" New topic
Author

Storage

Mohammed Niaz M.
Greenhorn

Joined: Apr 28, 2007
Posts: 27
--------------------------------------------
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

Joined: May 23, 2007
Posts: 24
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).
-------------------------------------------------------
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Storage