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

3 Answers 3

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; }
}
2
  • how can i retrieve a value from a method without using return ?
    – Riskhan
    Feb 17, 2012 at 7:01
  • if a String is, String[] value
    – Riskhan
    Feb 17, 2012 at 7:03
2

There is no pass by reference in Java.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.