-2

I'm trying to change the value of static variable that I passed to Klasa.method() function and sadly return value is ignored.

package com.company;

public class Klasa {
    public static int metoda(int x){
        x += 2;
        return x;
    }

}

public class Main {
    public static int i = 10;

    public static void main(String... args) {
        System.out.println(Main.i);
        Klasa.metoda(i);
        System.out.println(Klasa.metoda(i));
        System.out.println(i);
    }
}
David Brossard
  • 13,584
  • 6
  • 55
  • 88
Mr_t
  • 35
  • 5
  • You've chosen the wrong language for that. The `x` within `metoda` is a copy by value. – akuzminykh Mar 10 '21 at 22:12
  • 1
    What output are you getting and how is it different from what you expect? You print out `i`, so it prints `10`. You print out the return value of the method, so it prints `12`. Then you print out `i` again, so it prints out `10` again. What is confusing you? – Charlie Armstrong Mar 10 '21 at 22:13
  • 1
    Oh I see you're thinking of pass-by-reference. We have a canonical for this. – Charlie Armstrong Mar 10 '21 at 22:14
  • Yes, I was thinking of passing by reference, thanks Charlie – Mr_t Mar 10 '21 at 22:30

2 Answers2

0

You have a misunderstanding of how Java works... Passing in i to your method will not change the value of i so you have reassign the value returned by the method to i:

i = Klasa.metoda(i);
David Brossard
  • 13,584
  • 6
  • 55
  • 88
-1

You are only passing the value of i to your method. You could solve it simply by changing

Klasa.metoda(i);

to

i = Klasa.metoda(i);