Reputation: 1259
I know here is no pointer in Java. But how do I change a value in the calling scope? For instance, I want to write a function that takes an integer num, set the integer to 0 if it's greater than 21, otherwise do nothing. In the main, my code is as follow:
int a=34;
KillOver21(a);
System.out.print(a);
I expect an 0.
Upvotes: 3
Views: 148
Reputation: 41200
It is simply not possible, Java supports pass by value. int a
's value will be copied to the function.
You could use Object
instead of primitive where the reference value will be copied to your function by which you can get the actual object and modify it.
Upvotes: 3
Reputation: 1641
The simpliest way (quick&dirty) is to put value within an array
int holder[] = new int[]{ a};
KillOver21(holder)
System.out.printf( "value=[%d]", holder[0] );
void KillOver21(int holder[] ) {
holder[0] = 0;
}
Upvotes: 1
Reputation: 17622
Java is pass by value, so a copy of the parameter a is sent to the method, so modification to a
in the method will not affect the original argument a
in main
The max you can do is return int
from KillOver21(a)
method
int z = KillOver21(a); // This will return 0
System.out.print(z);
But you can achieve something like that with custom objects, say you have a class
class AHolder {
public int a;
}
then you can expect AHolder
instance to change
public static void main(String [] args) {
AHolder a = new AHolder();
a.a = 34;
killOver21(a);
System.out.println(a.a);
}
public static void killOver21(AHolder b) {
if(b.a > 21) {
b.a = 0;
}
}
Since in the latter (even if its Pass by Value) , the reference is copied and both reference point to same object. So changes made inside the killOver21
method actually changes the object.
Upvotes: 4
Reputation: 241641
Fundamentally impossible in Java, period. int
are immutable, and passed by value. You would need to create a mutable int
type:
class MutableInt {
private int value;
public MutableInt(int value) { this.value = value; }
public getValue() { return this.value; }
public setValue(int value) { this.value = value; }
}
Then:
void KillOver21(MutableInt m) {
if(m.getValue() > 21) { m.setValue(0); }
}
However, be aware the mutable types that represent concepts that are defined by their value rather than their identity are generally an extremely bad idea. But, this is the only way to achieve what you're trying to achieve. Again, I caution you with the strongest words: what you're doing is a bad idea. You should find another way.
Doc, it hurts when I do this.
Then don't do that!
Upvotes: 1