1

I want to change the variable value without changing it directly, In C or C++ we may use pointers or reference variable to do that since no pointer concept in java, how we can do that.
in C we may do like this

int var=10;
int *ptr;
ptr=&var;
*ptr++;
printf("%d",var);

output :11
Is there is any other way to do same thing in java ?

Thanks in advance.

Raj kumar
  • 153
  • 4
  • 13

1 Answers1

3

All the primitive types in Java (byte, short, int, long, float, double, boolean, char) are call by value, so with these, no, you can't do it. You can do it with objects though, as those are references.

Example:

public class MyInt {
    public int value;
}

public static void main(String args[]) {
    MyInt i1 = new MyInt();
    i1.value = 2;
    MyInt i2 = i1;
    i2.value++;
    System.out.println(i1.value);
}
CodedStingray
  • 390
  • 1
  • 10