Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

There is no pass by reference in Java.


Solution 3:

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.


Post a Comment for "Passing Reference As Parameter In Android"