There are two problems:

  1. Java uses pass by value, not by reference. Changing the reference inside a method won't be reflected into the passed-in reference in the calling method.
  2. Integer is immutable. There's no such method like Integer#set(i). You could otherwise just make use of it.

To get it to work, you need to reassign the return value of the inc() method.

integer = inc(integer);

To learn a bit more about passing by value, here's another example:

public static void main(String... args) {
    String[] strings = new String[] { "foo", "bar" };
    changeReference(strings);
    System.out.println(Arrays.toString(strings)); // still [foo, bar]
    changeValue(strings);
    System.out.println(Arrays.toString(strings)); // [foo, foo]
}
public static void changeReference(String[] strings) {
    strings = new String[] { "foo", "foo" };
}
public static void changeValue(String[] strings) {
    strings[1] = "foo";
}
Answer from BalusC on Stack Overflow
Discussions

java Integer reference - Stack Overflow
Most of the classes such as Integer that derive from Java's abstract Number class are immutable., i.e. once constructed, they can only ever contain that particular number. A useful benefit of this is that it permits caching. If you call: ... you get back a cached object, rather than a new object. This saves memory and increases performance. In the latter test case with a bare int argument, all you're seeing is how Java's variables are passed by ... More on stackoverflow.com
🌐 stackoverflow.com
Why does java not have pass by reference
To know "why", you'd probably need to ask the language designers. Perhaps more constructively, you could ask "What are some advantages of not having pass by reference in a language?" Not having a feature, especially if there exists workarounds like the ones you mentioned, can itself often be considered a feature: the feature of simplicity. Simpler languages can be easier to learn and reason about. I believe one of the goals of Java was to be a simpler and safer alternative to C++. They seemed to have made an attempt at minimizing the concept of pointers, and introducing "pass by reference" would have probably gone counter to that goal. More on reddit.com
🌐 r/java
76
0
July 12, 2021
How to do the equivalent of pass by reference for primitives in Java - Stack Overflow
I am trying to do something similar ... an integer? Because I have a method that returns a number but if I dont call it somewhere, it is not in use. 2015-11-15T11:36:00.377Z+00:00 ... Save this answer. ... Show activity on this post. ... then pass a reference to an instance of it. Note that a method that mutates state through its arguments is best avoided, especially in parallel code. ... Downvoted by me. This is wrong on so many levels. Java is pass by ... More on stackoverflow.com
🌐 stackoverflow.com
methods - Is Java "pass-by-reference" or "pass-by-value"? - Stack Overflow
For example: int *p; in P means ... to an integer. We don’t have this facility in Java, so it’s absolutely correct and technically legitimate to say it as an handle. Also, there are rules for pointer arithmetic in C. Which allows performing arithmetic operation on pointers with constraints on it. In C, we call such a mechanism of passing address and receiving them with pointer variables as pass by reference since we are ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-pass-integer-by-reference-in-java
How to pass integer by reference in Java - GeeksforGeeks
July 11, 2025 - Java is pass by value and it is not possible to pass integer by reference in Java directly. Objects created in Java are references which are passed by value.
🌐
TutorialsPoint
tutorialspoint.com › pass-an-integer-by-reference-in-java
Pass an integer by reference in Java
To pass an integer by reference in Java, try the following code − Example Live Demo public c
🌐
Real's HowTo
rgagnon.com › javadetails › java-0035.html
Pass an integer by reference - Real's Java How-to
Got it Sometimes you may need to pass an integer to be able to change its value. "integer" are always passed by value in Java. An easy way to pass by reference is to use a single element array.
🌐
Geek Interview
geekinterview.com › question_details › 12814
How would you pass a java integer by reference to another function
Passing by reference is impossible in JAVA but Java support the object reference so. Object is the only way to pass the integer by refrence.
Find elsewhere
🌐
Scaler
scaler.com › home › topics › pass by value and call by reference in java
Pass by Value and Call by Reference in Java - Scaler Topics
February 11, 2022 - Here, we can see that if we reinitialize the array object, which is passed in arguments, the original reference breaks(i.e., we have replaced the original object reference with some other object reference), and the array no longer is referenced to the original array. Hence the value in the main() method didn’t change. ... The modification of an object depends on the immutability of a Java class. The classes like Integer, String, Float, Double, Byte, Long, Short, Boolean, and Character are all immutable classes; hence, once created, no modification can be made on the same reference.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-is-pass-by-value-and-not-pass-by-reference
Java is Pass by Value, Not Pass by Reference | DigitalOcean
December 6, 2022 - and to do this it require to create a new instance of your class with field which will hold a variable with reference to your object. For example, you want to pass Integer to method and change it in the body of that method but there is no method to change value of Integer object.
🌐
Hero Vired
herovired.com › learning-hub › topics › call-by-value-and-call-by-reference-in-java
Call by Value and Call by Reference in Java : Hero Vired
Two integer objects, n1 and n2, are provided to the sum() method in this example. It is important to realise that Java passes the value of the reference (also known as pass by value of reference) rather than the reference itself.
🌐
Techcrashcourse
techcrashcourse.com › 2022 › 07 › call-by-value-and-call-by-reference-in-java.html
Call by Value and Call by Reference in Java
The values of num and var variable is stored at different memory locations. Hence, incrementing the value of parameter var inside "increment" method will not change the value of num. Call by reference method copies the address of an argument into the formal parameter.
🌐
Medium
medium.com › @nitishprasad › call-by-value-or-call-by-reference-a-mess-in-java-ce2636998db2
Call by value or call by Reference…. A mess in Java | by Nitish Prasad | Medium
May 10, 2019 - Initially you created a simple Plain old java object (POJO). In response to that JVM creates a actual object in Heap memory and give you a reference to that object so that you can manipulate it. But for primitive data type, there is no object and reference relationship. int contain its value , same for float , double. When you assign one object to other object, actually you are creating copy of the reference not the object. ... So as you know , when you pass by value something , its copy is created and passed to the function.
🌐
PrepBytes
prepbytes.com › home › java › call by value and call by reference in java
Call by Value and Call by Reference in Java
May 9, 2023 - Calling a method by reference means passing a reference (the variable’s location) as a parameter. Primitive data types (int, float, double, boolean, char, and so on) are always passed as values in Java, while non-primitive data types (class, object, array, string, and interface) are always passed as references.
Top answer
1 of 8
186

You have several choices. The one that makes the most sense really depends on what you're trying to do.

Choice 1: make toyNumber a public member variable in a class

class MyToy {
  public int toyNumber;
}

then pass a reference to a MyToy to your method.

void play(MyToy toy){  
    System.out.println("Toy number in play " + toy.toyNumber);   
    toy.toyNumber++;  
    System.out.println("Toy number in play after increement " + toy.toyNumber);   
}

Choice 2: return the value instead of pass by reference

int play(int toyNumber){  
    System.out.println("Toy number in play " + toyNumber);   
    toyNumber++;  
    System.out.println("Toy number in play after increement " + toyNumber);   
    return toyNumber
}

This choice would require a small change to the callsite in main so that it reads, toyNumber = temp.play(toyNumber);.

Choice 3: make it a class or static variable

If the two functions are methods on the same class or class instance, you could convert toyNumber into a class member variable.

Choice 4: Create a single element array of type int and pass that

This is considered a hack, but is sometimes employed to return values from inline class invocations.

void play(int [] toyNumber){  
    System.out.println("Toy number in play " + toyNumber[0]);   
    toyNumber[0]++;  
    System.out.println("Toy number in play after increement " + toyNumber[0]);   
}
2 of 8
30

Java is not call by reference it is call by value only

But all variables of object type are actually pointers.

So if you use a Mutable Object you will see the behavior you want

public class XYZ {

    public static void main(String[] arg) {
        StringBuilder toyNumber = new StringBuilder("5");
        play(toyNumber);
        System.out.println("Toy number in main " + toyNumber);
    }

    private static void play(StringBuilder toyNumber) {
        System.out.println("Toy number in play " + toyNumber);
        toyNumber.append(" + 1");
        System.out.println("Toy number in play after increement " + toyNumber);
    }
}

Output of this code:

run:
Toy number in play 5
Toy number in play after increement 5 + 1
Toy number in main 5 + 1
BUILD SUCCESSFUL (total time: 0 seconds)

You can see this behavior in Standard libraries too. For example Collections.sort(); Collections.shuffle(); These methods does not return a new list but modifies it's argument object.

    List<Integer> mutableList = new ArrayList<Integer>();

    mutableList.add(1);
    mutableList.add(2);
    mutableList.add(3);
    mutableList.add(4);
    mutableList.add(5);

    System.out.println(mutableList);

    Collections.shuffle(mutableList);

    System.out.println(mutableList);

    Collections.sort(mutableList);

    System.out.println(mutableList);

Output of this code:

run:
[1, 2, 3, 4, 5]
[3, 4, 1, 5, 2]
[1, 2, 3, 4, 5]
BUILD SUCCESSFUL (total time: 0 seconds)
🌐
Scientech Easy
scientecheasy.com › home › blog › call by value and call by reference in java
Call by Value and Call by Reference in Java - Scientech Easy
January 15, 2026 - Let’s take an example program to understand call by reference concept in Java. In the above program, we passed integer values to the parameters of a method. But in a real-time company project, we do not pass primitive values such as int, float, or double values to a method.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › java tutorial › java call by reference
Java Call by Reference | How Call by Reference works in Java | Examples
June 3, 2023 - This reference points to the address of our variable ‘a’. It will increment this value, and then when the function is called, it takes the value from this address. It will be 11 in this case as the inc function is increasing the value by 1. The value will be printed in the main. We can also create a copy of the reference variable. If a new object or variable is created for reference, it will not be affected as the primary address remains the same. We can check a few more examples on this, which will help us understand better: Swapping numbers in Java by using Call by Reference.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Top answer
1 of 15
31

I have created a question devoted to these kind of questions for any programming languages here.

Java is also mentioned. Here is the short summary:

  • Java passes it parameters by value
  • "by value" is the only way in Java to pass a parameter to a method
  • using methods from the object given as parameter will alter the object as the references point to the original objects (if that method itself alters some values).
2 of 15
29

One of the biggest confusions in the Java programming language is whether Java is pass by value or pass by reference.

First of all, we should understand what is meant by pass by value or pass by reference.

Pass by value: The method parameter values are copied to another variable and then the copied object is passed. That’s why it’s called pass by value.

Pass by reference: An alias or reference to the actual parameter is passed to the method. That’s why it’s called pass by reference.

Let’s say we have a class, Balloon, like below.

public class Balloon {

    private String color;

    public Balloon(){}

    public Balloon(String c){
        this.color=c;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

And we have a simple program with a generic method to swap two objects. The class looks like below.

public class Test {

    public static void main(String[] args) {

        Balloon red = new Balloon("Red"); // Memory reference 50
        Balloon blue = new Balloon("Blue"); // Memory reference 100

        swap(red, blue);
        System.out.println("red color="+red.getColor());
        System.out.println("blue color="+blue.getColor());

        foo(blue);
        System.out.println("blue color="+blue.getColor());

    }

    private static void foo(Balloon balloon) { // baloon=100
        balloon.setColor("Red"); // baloon=100
        balloon = new Balloon("Green"); // baloon=200
        balloon.setColor("Blue"); // baloon = 200
    }

    // Generic swap method
    public static void swap(Object o1, Object o2){
        Object temp = o1;
        o1 = o2;
        o2 = temp;
    }
}

When we execute the above program, we get following output.

red color=Red
blue color=Blue
blue color=Red

If you look at the first two lines of the output, it’s clear that swap method didn’t work. This is because Java is passed by value; this swap() method test can be used with any programming language to check whether it’s passed by value or passed by reference.

Let’s analyze the program execution step by step.

Balloon red = new Balloon("Red");
Balloon blue = new Balloon("Blue");

When we use the new operator to create an instance of a class, the instance is created and the variable contains the reference location of the memory where the object is saved. For our example, let’s assume that “red” is pointing to 50 and “blue” is pointing to 100, and these are the memory location of both Balloon objects.

Now when we are calling the swap() method, two new variables o1 and o2 are created, pointing to 50 and 100, respectively.

So the below code snippet explains what happened in the swap() method execution.

public static void swap(Object o1, Object o2){ // o1=50, o2=100
    Object temp = o1; // temp=50, o1=50, o2=100
    o1 = o2; // temp=50, o1=100, o2=100
    o2 = temp; // temp=50, o1=100, o2=50
} // Method terminated

Notice that we are changing the values of o1 and o2, but they are copies of “red” and “blue” reference locations, so actually, there isn't any change in the values of “red” and “blue” and hence the output.

If you have understood this far, you can easily understand the cause of the confusion. Since the variables are just the references to the objects, we get confused that we are passing the reference, so Java is passed by reference. However, we are passing a copy of the reference and hence it’s passed by value. I hope it clears all the questions now.

Now let’s analyze the foo() method execution.

private static void foo(Balloon balloon) { // baloon=100
    balloon.setColor("Red"); // baloon=100
    balloon = new Balloon("Green"); // baloon=200
    balloon.setColor("Blue"); // baloon = 200
}

The first line is the important one. When we call a method, the method is called on the Object at the reference location. At this point, the balloon is pointing to 100 and hence it’s color is changed to Red.

In the next line, the balloon reference is changed to 200 and any further methods executed are happening on the object at memory location 200 and is not having any effect on the object at memory location 100. This explains the third line of our program output printing blue color=Red.

I hope the above explanation clears all the questions. Just remember that variables are references or pointers and its copy is passed to the methods, so Java is always passed by value. It would be more clear when you will learn about heap and stack memory and where different objects and references are stored.