3

I am newbie in java/android. I am a c/c++ developer. May i know how to pass a reference as parameter in android. An illustrative c sample code shown below

void main()
{
  int no1 = 3, no2 = 2, sum = 0;
  findsum( no1, no2, sum );
  printf("sum=%d", sum );
}

void findsum( int no1, int no2, int& sum )
{
  sum = no1 + no2;
}

please suggest me a solution

thanks

onof
  • 16,907
  • 7
  • 47
  • 84
Riskhan
  • 4,242
  • 11
  • 46
  • 71

3 Answers3

7

You cannot pass an int as reference in Java. int is a primary type, it can be passed only by value.

If you still need to pass an int variable as reference you can wrap it in a mutable class, for example an int array:

void findsum( int no1, int no2, int[] sum )
{
  sum[0] = no1 + no2;
}

Anyway, I strongly suggest you to refactor your code to be more object oriented, for example:

class SumOperation {
   private int value;

   public SumOperation(int no1, int no2) {
      this.value = no1 + no2;
   }

   public int getReturnValue() { return this.value; }
}
onof
  • 16,907
  • 7
  • 47
  • 84
1

There is no pass by reference in Java.

newacct
  • 115,460
  • 28
  • 157
  • 222
0

This is how I solved this problem:

// By using a wrapper class.
// This also works with Class objects.
class IntReturn {
    public int val;
}

// For example:
class StringReturn {
    public String val;
}

class Main {
    public static void main (){
        IntReturn iRtn = new IntReturn();
        
        if(tryAdd(2, 3, iRtn)){
            System.out.println("tryAdd(2, 3): " + iRtn.val);
        }
    }

    public static boolean tryAdd(final int a, final int b, final IntReturn iRtn){
        iRtn.val = a + b;

        return true;  // Just something to use return
    }
}

I have a personal library of these types of classes for this purpose. Lambdas are another reason for these classes as you need to have a 'final' variable to get a value out of a Lambda, other than by return statement.