How to pass value by reference in java

public class JavaApplication6 { public static void a(int b) { b++; } 

I call the function a and pass the variable b to increase it as a reference to C ++ ( &b ). Will this work? If not, why?

  public static void main(String[] args) { int b=0; a(b); System.out.println(b); } } 
+6
source share
4 answers

As long as you cannot accomplish this with int (a primitive type for an integer), you can do something very similar to AtomicInteger . Just call the getAndIncrement method of the class instance. Something like that:

 public static void a(AtomicInteger b) { b.getAndIncrement(); } 

(Note that you also cannot do this with java.lang.Integer, because java.lang.Integer is an immutable class.)

+3
source

First of all: Java does not allow passing by reference. In addition, out-parameters (when the calculations / results of a function are placed in one or more variables passed to it) are not used; instead, something is return ed from a method like this:

 b = a(b); 

Otherwise, in Java, you pass objects as pointers ( which are incorrectly called references ). Unfortunately (in your case) most types matching int ( Integer , BigInteger , etc.) are immutable, so you cannot change the properties of an object without creating a new one. However, you can 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++; } 

When you run this code on the console, the following will be printed:

 3 

At the end of the day, using the above requires a strong argument as part of the programmer.

+3
source

You cannot do this with primitive types such as int, because Java passes primitives by value. Just wrap b in a mutable container object:

 class Holder { int b; } 

Now you can change the value by doing:

 public static void a(Holder h) { h.b++; } 

However, you should consider working with immutable objects , which are generally considered useful in Java, to avoid side effects and concurrency problems.

+1
source

You cannot pass a value by reference in Java. If the primitive is passed to the method, the JVM passes it by value. If this is an object that is sent to the method, the JVM creates a copy of the link. Since this is a โ€œcopy,โ€ the modification will not change the initial object. However, there is a workaround, such as using AtomicInteger, suggested in previous posts.

0
source

All Articles