0

In Java, is it possible for a calling method to get the value of a local variable inside the called method without returning it?

See below in C, where I can use pointers to change the value of the local variable of the fun function.

#include <stdio.h>

int main(void) {

    int* a;
    a = malloc(sizeof(int));
    *a = 10;

    printf("before calling, value == %d\n",*a);
    fun(a);
    printf("after calling, value == %d",*a);

    return 0;
}

int fun(int* myInt)
{
    *myInt = 100;
}

Can I do something similar in Java. I did try, but wasn't able to.

public class InMemory {

    public static void main(String[] args) {
        int a = 10;

        System.out.println("before calling ..."+a);
        fun(a);
        System.out.println("after calling ..."+a);
    }

    static void fun(int newa)
    {
        newa = 100;
    }
}
saltandwater
  • 791
  • 2
  • 9
  • 25
  • Java doesn't have pointers. If this was possible, it would mean the 'local variable' is not local, which is a contradiction. – Aganju Jul 02 '16 at 19:20

2 Answers2

0

int and Integer are not mutable. You could pass in a reference to a collection and modify the contents of it, or use a mutable implementation of an integer such as AtomicInteger if you're that keen on it.

public class InMemory {
    public static void main(String[] args) {
        AtomicInteger a = new AtomicInteger(10);

        System.out.println("before calling ..." + a);
        fun(a);
        System.out.println("after calling ..." + a);
    }

    static void fun(AtomicInteger newa) {
        newa.set(100);
    }
}
rich
  • 18,987
  • 11
  • 75
  • 101
0

You can use method as setter for your global variable to get the local variable of that function.

public class InMemory {

static int g=10;  // global in class

    public static void main(String[] args) {

    System.out.println("before calling ..."+g);
    fun();
    System.out.println("after calling ..."+g);
    }

    static void fun()
    {
    int l = 100; // local in fun
g = l; // assign value to global 
    }
}
Shahbaz Hashmi
  • 2,631
  • 2
  • 26
  • 49
  • thanks for the response. a)It doesn't compile, the int g = 10; declaration should be before main, and should be static int g = 10; b)As I mentioned in the original post, I would like the variable to be local. – saltandwater Jul 02 '16 at 19:45
  • I just edited your code. Just trying to explain there is no pointer in java. So you should do something like this. – Shahbaz Hashmi Jul 02 '16 at 19:50