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
  • 22,721
  • 17
  • 71
  • 112

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
  • 714,442
  • 84
  • 1,110
  • 1,523
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
  • 21,561
  • 9
  • 74
  • 114
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,752
  • 7
  • 47
  • 88