I'm passing a variable from main to a method in another class. I thought that the variable could be changed inside the method, without being changed in main. Using loads of print statements, I've found that my 'updatePosition' method actually modifies the variable 'newVelocity' and the modification somehow finds its way back to the main class. How do I stop this?? Here's the loop in the main class where the method is called:
//do{
projectile.updatePosition(newPosition, newVelocity, timeStep, g);
System.out.println("This is newVelocity");
newVelocity.print(); //This variable has been modified!!! Doesn't print what it should
projectile.getNewPosition();
System.out.println("This is new position");
newPosition.print();
newPositionForNewtonsLaw = newPositionForNewtonsLaw.add(distance,newPosition);
newG = earth.aDueToGravity(earthMass, earthRadius, newPositionForNewtonsLaw);
projectile.updateVelocity(newVelocity, timeStep, g, newG);
newV = projectile.getNewVelocity();
System.out.println("new velocity");
newV.print();
g=earth.aDueToGravity(earthMass, earthRadius, newPositionForNewtonsLaw);
System.out.println("This is newG");
newG.print();
g.print();
newVelocity = projectile.getNewVelocity();
positionX=newPosition.getX();
positionY=newPosition.getY();
System.out.println(positionX);
System.out.println(positionY+"y");
//}while (positionY>0);
And here's the method that's modifying the variable, even though I'm sure it shouldn't!
public PhysicsVector updatePosition(PhysicsVector initialPosition, PhysicsVector initialVelocity, double timeStep, PhysicsVector a){
PhysicsVector v = new PhysicsVector();
v=initialVelocity;
a.scale(0.5*timeStep);
v.increaseBy(a);
v.scale(timeStep);
System.out.println("This is initialVelocity");
initialVelocity.print();
initialPosition.increaseBy(v);
return initialPosition;
}
newVelocity is an object (from a class to make vector) and I don't know if it can be declared public, static, private etc, or whether any of those things would actually help.