-1

I've been searching around for a few minutes and wasn't able to find a question that resembles mine. Just in case if this is a question that has been asked before, I am sincerely sorry and it's unintentional.

I'm trying to change the static variable's value that is passed in as a parameter. So there is this block of code:

public int check(int row, int column, char ch, Color color, int score) {

    this.row = row;
    this.column = column;
    this.ch = ch;
    this.color = color;
    this.score = score;
    flag = 0;

    if (something){
        do stuff
        score++;
    }
}

and there are these static variables are passed in for int score:

public static int player1Score;
public static int player2Score;

The method is supposed to be called via an event handler, and the button that they press determine whether the player1Score or the player2Score is passed as a parameter. It would be easy if it was just a single variable that is being passed as a parameter, but it is two or more at this point and can't think of any other way except making duplicate if-statements and each having them as player1Score++ and playr2Score++.

There are like 35 if statements that check the condition to do score++, and I just wanted to ask as if there is a way to change the value of the parameter itself.

Two static score variables are in a different class.

Help would be very appreciated.

Thanks.

vinS
  • 1,417
  • 5
  • 24
  • 37
Ure
  • 31
  • 1
  • 3
  • Java types such as int, long, double, etc. are [passed by value](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value). You can use the return type (`int`) to return the modified score value and assign it to your static variable by caller. I can suggest an answer, but need to know what is returning from this `check` method. – isuru89 Dec 09 '18 at 01:45
  • 1
    You should reconsider your architecture. Most likely, you don't even need static variables. To store player's score, you can use map, where key is player number and value is player score, you can store data for many players – user1209216 Dec 09 '18 at 01:51

1 Answers1

1

As @isuru89 said, it is passed by value.

Because you define primitive type int score in you check method, so this variable is stored in the stack of check method. Any changes for this variable will not be seen by others unless you return it.

There is a good article java memory model you can reference.

frank
  • 1,169
  • 18
  • 43