memory address?

DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: memory address?

  1. #1
    Join Date
    Oct 2004

    Unhappy memory address?


    Here is the code:

    import java.util.*;

    public class test{

    public static void main(String args[]) throws IOException

    BufferedReader stdin = new BufferedReader( new InputStreamReader ( ));

    String mystr = new String("1");




    public static void string(String str){

    str = new String("2");



    I just wonder why mystring value is not "2"??
    There might be somehow the two variables mystring and str has different memory address, but I don't know why? How can I make "mystring" changed to "2"??


  2. #2
    Join Date
    Feb 2004
    you cant. string is immutable.

    i'll explain what goes on, line by line. it will help to think of java objects as some object, like a ball. it will help to think of the named variable you give as being like a piece of paper tied to the object with string.. a tag, that you have a hold of

    now, yu make a new string, and somewhere in memory comes the word "1", tied to it is a label tag, mystr:


    you call a method with it, passing in the label. now, your method has the parameter named as String str.. and just like String myStr, this also attaches a label to our object in memory.. note it attaches to the object, NOT your tag:




    not that it would matter but.. you need to be clear that one object now has 2 labels (see above above)

    then you make a new object and reattach the str tag to the new:

    mystr--------("1")           str------("2")
    then the method ends, str goes out of scope and the label is destroyed:

    mystr--------("1")                      ("2")

    the new string "2" is now orphaned and will be garbage collected; it's dead

    and mystr is still attached to "1"

    this cannot be violated.. string cannot be changed once created..
    only a method that works on the object will show a change. as soon as you use the "new" keyword, you are not changing the object; youre making another
    The 6th edict:
    "A thing of reference thing can hold either a null thing or a thing to any thing whose thing is assignment compatible with the thing of the thing" - ArchAngel, et al.
    JAR tutorial GridBag tutorial Inherited Shapes Inheritance? String.split(); FTP?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
Latest Articles
Questions? Contact us.
Web Development
Latest Tips
Open Source

   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center