[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 173
  • Last Modified:

Can a Variable be populated from another method in another class.

I've ran across something that I've never seen in Java before.  I step throught somebody's code to get a line of data:
public class VendorMaster
{
next = loaddata.getLine(currentLine);
}

public class LoadData
{
public boolean getLine(byte[] line)
{
...
line is populated here
return gotnext;
}

When I step through the code in VendorMaster after executing getLine, currentLine is populated!  I didn't know you can populate a variable in the called method and make its contents visible in the calling class without actually returning it back in "return" statement.  Why is this happening?  Is this safe to implement especially with having multiple threads?  Thanks.
0
Mero
Asked:
Mero
  • 3
2 Solutions
 
jimmackCommented:
currentLine is passed across as a reference to the beginning of the array, so when the LoadData class writes to it, it's writing to the same memory space.

"currentLine" and "line" are referring to the same block of memory.
0
 
imladrisCommented:
Needing a return statement is true for "primitive" variables (int, long, byte, char etc.). Others (arrays or objects) are passed by reference.

Whether this will pose a challenge w.r.t. multiple threads or not depends on "where" the currentLine is. If it is a shared resource (usually or global or member variable) that multiple threads are accessing, you will need to guard its access with syncronization blocks. However, if currentLine is a purely local, temporary, variable located on the stack, then multithreading will have no impact. Each thread has its own stack, after all.
0
 
jimmackCommented:
Good catch imladris ;-)  I didn't read the last sentence :-(
0
 
jimmackCommented:
:-)
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now