0

Possible Duplicate:
pass by reference in java

I am new to java. I tried to search a lot for my query but could not find. Please help me if you know. I have a function:

boolean func(int a, int b, myclass obj1, myclass2 obj2)
{
    ...
}

void caller() {
    int a = 0, b=0;
    myclass obj1 = null;
    myclass1 obj2 = null;
    func(a,b,obj1,obj2);
    if (a == 5 && b ==2)
    {
        ...
    }
}

what should i do such that all passed variables have the value in caller function which was given by function func?

Community
  • 1
  • 1
user967491
  • 121
  • 1
  • 7
  • Java passes by value, so everything passed from `caller` to `func` is a copy (of primitives or references). Can you explain what you are really doing in `func`, so that we can come up with better approaches to what you're trying to do? – wkl Nov 03 '11 at 17:36
  • 1
    You already asked this question and it was closed as a duplicate last time too. – John B Nov 03 '11 at 17:40
  • @JohnB Yikes... Good duplicate detective work. One dupe, okay. But trying it again? – G_H Nov 03 '11 at 17:42

2 Answers2

0

I think you're trying to use pass-by-reference and use that to change the values of your variables through func. That can't be done in Java. It's strictly pass-by-value. Even when passing an object as a parameter, what you're actually passing is the reference value. So doing this:

func(Object o) {
    o = "test";
}
...
other() {
    Object a = new Object();
    func(a);
}

... won't have altered the a reference. It's still pointing to that Object instance rather than String "test". Method func has merely overwritten the local variable o that was given the reference value of a when it was called.

I suggest you either encapsulate your variables in some class that you pass into your method, or return from the method that takes an argument list, or rethink your design.

G_H
  • 11,739
  • 3
  • 38
  • 82
0

Java does not work that way. When a and b are passed to func, copies are made. func can change the values of those copies internally, but when it returns, the original a and b will be unchanged.

I don't know what a and b represent, but lets say they are coordinates. You can do this:

class Coordinates {
  int x;
  int y;
  // setters and getters omitted...
}

boolean func(Coordinates coords, myclass obj1, myclass2 obj2) {
...
}

Or since they start out as zero, perhaps this:

Coordinates func(myclass obj1, myclass2 obj2) {
  Coordinates coords = new Coordinates();
  ...
  return coords;
}
SingleShot
  • 18,821
  • 13
  • 71
  • 101