Georgi Tonchev Georgi Tonchev - 5 months ago 19
Java Question

Java: Variable is not incrementing

I have three classes: Movement, Collision and Variables(The Variables class is where I store my variables and all of them are public and static. Considering I am new to java I don't really understand what the static keyword does, so my problem might be with the static keyword.). In my Collision class there is a method which checks for collision within the map. Now this method works perfectly:

public void checkCollision(int x, int y)
{

if (x == 100){
Variables.collisionRight = true;

} else {
Variables.collisionRight = false;
}
}


Here I have a method in my Movement class which does not work:

public void playerMovement (int x, int y)
{
if (RightKeyPressed == true & collisionRight == false) {
x += Variables.speed;

}
}


Here is how i call these methods:

someObject.checkCollision(Variables.playerX, Variables.playerY);
someOtherObject.playerMovement(Variables.playerX, Variables.playerY);


Seems to me the problem is that this line:

x += Variables.speed;


If i change

x


to

Variables.playerX


Everything works fine, but that's not how I want it to work.

It's not working. Which basically should be (Variables.playerX += Variables.speed)
All the methods are samples.

I want to know why is my x (Variables.playerX) variable not incrementing by 3(which is my Variables.speed variable);

NPE NPE
Answer Source

What is happening is that Variables.playerX is getting passed by value as x. When the function modifies x, it is effectively modifying a local copy of Variables.playerX.

For further discussion, see Is Java "pass-by-reference" or "pass-by-value"? and Java is Pass-by-Value, Dammit!

One way to address this is by passing (a reference to) the Variables object instead of x and y:

public void playerMovement (Variables vars)
{
    if (RightKeyPressed && !collisionRight) {
        vars.x += vars.speed;
    }
}

P.S. Note how I rewrote the if condition. While what you have is not incorrect, idiomatically we don't explicitly compare booleans against true and false. Also, && and || are preferred over & and | in boolean contexts because they short-circuit.