• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic