1

I would like to be able to access a variable passed to my method. I know C might have has some kind of way to pass the address of something as an argument, then refer to that as a pointer and be able to use the variable. Anyway, here's an example.

void myFunction(address to variable) {
    *variable = "example";
}

Then call it as:

myFunction(&somevariable);
Matt
  • 21,273
  • 14
  • 68
  • 109

3 Answers3

5

There is no way to pass arguments by reference or by pointer in Java, so the only way to achieve the effect that you would like is passing a mutable object, and changing its value inside the method that you call:

public class ChangeableInt {
    private int number;
    public ChangeableInt(int value) {number = value;}
    public int get() {return number;}
    public void set(int value) {number = value;}
}

With this class in hand, you can do this:

void myFunction(ChangeableInt arg) {
   arg.set(42);
}
...
ChangeableInt val = new ChangeableInt(123);
myFunction(val);
System.out.println(val.get()); // prints 42
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
1

What you need is a simple wrapper template class...

class ObjWrapper<T> {
  T value;

  void setValue(T val) {
    value=val;
  }

  T getValue() {
    return value;
  }
}
Dariusz
  • 20,650
  • 8
  • 71
  • 109
0

something like

 class Myclass{
    int x=15;

    System.out.println(x) //15

    public static void main(String... ){

    Myclass obj = new Myclass()
    Myclass newRef =  method(obj)
    System.out.println(newRef.x)   //20




    }
   static Myclass method(Myclass ref){
       ref.x=20

    return ref
  }  
    }//class

Note that in 'obj' is a reference to the object resides somewhere in heap.

navyad
  • 3,533
  • 6
  • 43
  • 78