2

Am trying to change the value of an variable when it is passed as an argument to the function, but the original value remains the same, so is it possible to change?(i,e in the below code i want the value of x to be 11)

public  class Runy  {

public static void main(String [] args) 
{


    int x=10;
    int y=change(x);

    System.out.println(x);
    System.out.println(y);

}
public static int change(int a)
{
    a+=1;
    return a;
}

}

Rénald
  • 1,412
  • 12
  • 29
prabhakar Reddy G
  • 1,039
  • 3
  • 12
  • 23

5 Answers5

2

i,e in the below code i want the value of x to be 11)

With your current code, it won't possible but if you want to change the value of x, you don't need y then and simply you can do

 int x=10;
 x=change(x); // store the return value of change back to 'x'
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

You can change the elements of arrays passed as arguments or the fields of objects passed as arguments.

public static void change(int[] a) {
    a[0] += 1;
}

could be used like this:

int a[] = new int[1];
a[0] = 10;
change(a);
System.out.println("a[0] = " + a[0]);

or

static class A {
    int val;
}

static void change(A a) {
    a.val += 1;
}

could be used like this:

A a = new A();
a.val = 10;
change(a);
System.out.println("a.val = " + a.val);
WillShackleford
  • 6,918
  • 2
  • 17
  • 33
0

You cannot do that that way ... never try to change a parameter value !

do something like this instead :

public static int change(int a)
{
    return a + 1;
}

and in your main method :

x = change(x);
Pras
  • 1,068
  • 7
  • 18
0

When you pass a variable with a primitive data type (e.g. int, boolean, float etc.). The value is passed to the method, not a reference to the value. If you would like to change the original variable you have two options: pass the new value back from the method; create a class that wraps the value.

Option 1:

int x = 10;
x = change(x);

int change(int x) {
    return x + 1;
}

Option 2:

class X {
    private int x;
    int getX() {
        return x;
    }

    void setX(int x) {
        this.x = x;
    }
}

X x = new X();
x.setX(10);
change(x);

void change(X x) {
    x.setX(x.getX() + 1);
}
sprinter
  • 27,148
  • 6
  • 47
  • 78
  • ok, even when i pass the wrapper class object, the value is not changing(assuming that the value of the reference is passed for non primitive data types) – prabhakar Reddy G Oct 15 '15 at 07:27
0

It is not possible for a Java method to alter variables passed to it as arguments. After running this code:

int x = 10;
change(x);
System.out.println(x);

x will always contain 10 - there is nothing you can write in change to make it any other value.

As an alternative, you could make change return the new value, and use

x = change(x);
user253751
  • 57,427
  • 7
  • 48
  • 90