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.

8
  • 1
    No you can't ;) And why would you do that in Java ? Commented Jul 24, 2017 at 11:38
  • In Java everything is a reference (slap me if I'm slightly off). Commented Jul 24, 2017 at 11:38
  • Java has pointers, but you cannot manipulate them like in C++ or C Commented Jul 24, 2017 at 11:39
  • @TimBiegeleisen can you please give me simple code snippet using reference.please Commented Jul 24, 2017 at 11:39
  • @KennethClark how can we implement.any example Commented Jul 24, 2017 at 11:40

1 Answer 1

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); } 
Sign up to request clarification or add additional context in comments.

5 Comments

your example is missing
sorry messed up, added it now ^^
Example please.
what does it print?
it prints 3, as bothi1 and i2 are references to the same object

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.