Get the value of the local variable from the method called no return

advertisements

This question already has an answer here:

  • Is Java “pass-by-reference” or “pass-by-value”? 71 answers

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;
    }
}


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);
    }
}