public class JavaApplication6 {
public static void a(int b)
{
b++;
}
I am calling the function a
and passing the variable b
with the intention of incrementing it like a C++ reference (&b
). Will this work? If not, why?
public static void main(String[] args) {
int b=0;
a(b);
System.out.println(b);
}
}
While you can't really accomplish that with int
(the primitive type for integer), you can accomplish something very similar with AtomicInteger. Simply invoke the getAndIncrement method on an instance of the class. Something like this:
public static void a(AtomicInteger b) {
b.getAndIncrement();
}
(Note that you also can't do this with java.lang.Integer, because java.lang.Integer is an immutable class.)
First of all: Java does not allow for pass-by-reference. Further, out-parameters (when a function's calculations/results are placed in one or more of the variables passed to it) are not used; instead, something is return
ed from a method like so:
b = a(b);
Otherwise, in Java, you pass objects as pointers (which are incorrectly called references). Unfortunately (in your case) most types corresponding to int
(Integer
, BigInteger
, etc.) are immutable, so you cannot change the properties in the object without creating a new one. You can, however, make your own implementation:
public static class MutableInteger {
public int value;
public MutableInteger(int value) {
this.value = value;
}
}
public static void main(String[] args) {
MutableInteger b = new MutableInteger(2);
increment(b);
System.out.println(b.value);
}
public static void increment(MutableInteger mutableInteger) {
mutableInteger.value++;
}
The following will be printed to the console when this code is run:
3
At the end of the day, using the above requires a strong argument on the programmer's part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With