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:
Exception in thread
"main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: variable a
location: class test.Test
Java Result: 1
But if you use that code
The result would be
because b has the same refernce to the String object as a has.