Skip to content
Advertisement

passing reference as parameter in android

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

Advertisement

Answer

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; }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement