Results 1 to 2 of 2
- 02-09-2011, 04:26 PM #1
Member
- Join Date
- Feb 2011
- Posts
- 4
- Rep Power
- 0
Elementary question on variable references
I'm new to Java and just want to make sure I understand when references to objects remain valid. For example, the following code illustrates the question I have in mind.
Java Code:class MyTest { public static void main(String[] args) { MyClass foo = new MyClass(); initialize(foo); System.out.println(foo.myString); } static void initialize(MyClass foo) { foo.setString("Hello World"); } } class MyClass { String myString; void setString(String str) { myString = str; } }
The program compiles and gives the expected output "Hello World." The question is, does Java guarantee the reference to myString will remain valid? The potential problem is that the original string "Hello World" goes out of scope when initialize() is exited.
My understanding is that Java is smart about this, and that it won't free or overwrite the memory for "Hello Word" until there are no more in-scope references to it anywhere. But I just want to make sure before I mess up too much code.
- 02-09-2011, 04:35 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 14,422
- Blog Entries
- 7
- Rep Power
- 29
Yup, Java is 'clever' enough not to lose a reference to your literal String, i.e. when you call your initalize( ... ) method the stack has a reference to your String; in your method the object sets its myStr variable to your String; note that all the time a reference is available to your String so the garbage collector won't touch it.
kind regards,
JosBuild a wall around Donald Trump; I'll pay for it.
Similar Threads
-
Handling Exception - elementary question
By kracer in forum New To JavaReplies: 2Last Post: 05-06-2010, 11:47 PM -
Help me finish an instance method which references a class variable?
By trueblue in forum New To JavaReplies: 20Last Post: 06-03-2009, 05:33 PM -
Elementary problems
By mgm2010 in forum New To JavaReplies: 6Last Post: 02-01-2009, 08:33 PM -
Elementary Quesions
By hitmen in forum New To JavaReplies: 6Last Post: 10-21-2008, 12:23 AM -
Simple Question Making a Variable Accessable throught the code
By 2o2 in forum New To JavaReplies: 1Last Post: 10-02-2008, 03:06 AM
Bookmarks