1

I don't know why can't I modify a variable in Java, take my code, please help me

public class Main {
    public static void main(String[] args){
        int number = 1;
        change(number);
        System.out.println(number); // it should print 100
    }

    public static void change(int number){
        number = number * 100;
    }
}

Now, why when I use an array it does work?

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};

        // prints 100, 200, 300
        for(int i = 0; i < numbers.length; i++){
            System.out.println(numbers[i]);
        }
    }

    public static void change(int[] numbers) {
        for(int i = 0; i < numbers.length; i++){
            numbers[i] = numbers[i] * 100;
        }
    }
}
  • Because you pass a *copy of the value* to the `change` function. – Some programmer dude Dec 28 '20 at 05:44
  • Please read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please learn how to [edit] your question. – Some programmer dude Dec 28 '20 at 06:00
  • Consider `Integer[]` array instead of `int[]`, that way you would pass Integer object which is passed by reference to the `change` method instead of primitive variable `int` which is passed by value – Youans Dec 28 '20 at 06:27

1 Answers1

1

It's the Java Basics! Java is always pass-by-value.

In the first block where you are passing a primitive integer value 1 to function "change(int number)", only the value is passed. But the variable "int number" in the main function & in the change function is referencing two different memory references. i.e. As those two are not the same memory reference, those two values will be different. So if you print its value in the main function it will be 1 (original) & if you print its value in the change function itself then it will be 100 (copied value), but back in the main function, its value will be original variable's value i.e. 1.

Now, in the second block, where you are passing Array Object to change function there you are passing the reference of the array object. Java creates copies of the references so logically there are pointing to the same memory location. Thus any changes to it will be reflected in the original & copied (basically the same).

Prasad Tamgale
  • 325
  • 1
  • 12