ProgramWindowJava

memory address?

Hi

Here is the code:

import java.io.*;
import java.util.*;

public class test{


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

BufferedReader stdin = new BufferedReader( new InputStreamReader ( System.in ));

String mystr = new String("1");

string(mystr);

System.out.println(mystr);



}

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"??

Thanks

Replay:memory address?
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:

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

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:

mystr-------("1")--------str

not:

str------mystr------("1")

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:

Code:
mystr--------("1") str------("2")

then the method ends, str goes out of scope and the label is destroyed:

Code:
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

[Previous] My first program.
[Next] executable java file

Google


Java

executable java file
Bitwise comparison?
Can't figure out Static Error?
Help!! using recursion to search an array
Encrypt / Decrypt homework help
Menus
help!!!!!!!!!!!!!!!
How to access JSpinner's JTextField?
easy questions
recursion/iterator problem
repainting the whole frame??
Help Wih Chessboard Problem
Format US currency
Applet:How do I get a background image.
ArrayList printout?
Get rid of that comma in my JSpinner!!!
calling other classes
Variables not visable?
return statement trouble
how to setup showConfirmDialog?