1

Could someone explain why this prints 15 and not 0? From what I am understanding, when passBall is called, it is called with ball as its parameter and when catchBall is called with ball also as its parameter, so when we are in catchBall, we have a reference to ball (the original ball from playGame) and so what I don't understand is when ball = newBall in catchBall, why doesn't ball.getSpeed() equal to 0 when we reach the print statement in playGame()?

public static void main(String[] args) {
    Game g = new Game();
    g.playGame();
}
public class Ball {

    private int speed;

// This creates a ball with the given speed
    public Ball() { 
    
    }

//This sets the speed of the ball to the given speed
    public void setSpeed(int speed) { 
        this.speed = speed; 
    }

//This returns the speed of the ball
    public int getSpeed() { 
       return speed; 
    }
}


public class Game {
public void playGame() {
    Ball ball = new Ball();
    ball.setSpeed(10);
    passBall(ball);
    System.out.println(ball.getSpeed());
}

public void passBall(Ball ball) {
    Ball newBall = ball;
    ball.setSpeed(ball.getSpeed() + 5);  
    catchBall(ball);  
}

public void catchBall(Ball ball) {
    Ball newBall = new Ball();
    newBall.setSpeed(40);
    newBall.setSpeed(0);
    ball = newBall;
}

}

gsong
  • 11
  • 1
  • 5
    Does this answer your question? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – maloomeister Sep 17 '21 at 07:26
  • 1
    `ball = newBall;` doesn't do what you think it does ... `ball` is not changed at all there, at least not the original one ... what is passed in `catchBall(Ball ball)` as a `ball` is a copy of the variable `ball` – lealceldeiro Sep 17 '21 at 07:26
  • If you want it to be changing its value you should declare ball as a global variable otherwise what you are changing is a copy of it. – MadMax Sep 17 '21 at 07:28

1 Answers1

0

You create ball A. On passBall you are setting the value of ball A, which is 10 + 5. On catchBall you are creating a new object, ball B, and then you are setting it's value to 0. On play game you are printing the value of ball A. That's why you get 15.

Everytime you do new Ball() you are creating a new object and if you want to print it's value, you must return it.

Also, using different variable names every time you create a new object will help you understand it better

wrist88
  • 1
  • 1