• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can you return a local variable value from a function in Java?  RSS feed

 
Angus Comber
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For example this compiles and runs ok:
import java.util.*;

public class myclass {

public static void main(String[] args)
{
myclass mc = new myclass();
System.out.println(mc.getMyString());
}

public String getMyString() {
Date dt = new Date();
String thestring = dt.toString();
return thestring;
}
}

Is this ok in Java? I am wondering because thestring will go out of scope when function returns.

If I use return dt.toString() then dt will go out of scope when the function returns. Was wondering if this is ok in Java - as new to the language.
 
Bernhard Waidacher
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Angus Comber wrote:
Is this ok in Java? I am wondering because thestring will go out of scope when function returns.

If I use return dt.toString() then dt will go out of scope when the function returns. Was wondering if this is ok in Java - as new to the language.


Of course, it is totally OK and will work fine, for both versions.

In that case it won't go out of scope, because the function will the refernce, and then the new refernce which is created will point to the same object.
An object and a refernce is not the same.

For better understanding, I will show you an example where you would go out of scope.


In this example you would go out of scope, and you would get an exeption:
something
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: variable a
location: class test.Test
at test.Test.getAnotherString(Test.java:27)
at test.Test.main(Test.java:35)
Java Result: 1

But if you use that code


The result would be
something
something2
because b has the same refernce to the String object as a has.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!