# Random Class in Java

• Java
I'm trying to program a java simulation of some particles in a box. Anyways I want to initialize the particles with random velocities such that on average they're distributed around some velocity.

To do this I was thinking about using the nextGaussian() method.

Anyways I was initializing my particles with something like (in a simplified version):

Code:
Random r = new Random();
double avg = 10;
Particle a = new Particle(xpos,ypos, r.nextGaussian()+avg,r.nextGaussian()+avg);

Where particle takes in 4 doubles: xpos,ypos,xvel,yvel.

Anyways I'm worried about the way java stores the variables. I'm worried that my particle class will store the addr to r.nextGaussian rather than just a number. This would be bad since then everytime I would call the xvel or yvel the number would change.

Is that assessment correct and does anyone know of a way to fix it if this is correct?

Mark44
Mentor
You didn't show the definition of the Particle class, but presumably it has four member variables of type double that the constructor sets. After a given Particle instance is constructed, the xvel and yvel values won't change unless some member function changes them.

chiro
I'm trying to program a java simulation of some particles in a box. Anyways I want to initialize the particles with random velocities such that on average they're distributed around some velocity.

To do this I was thinking about using the nextGaussian() method.

Anyways I was initializing my particles with something like (in a simplified version):

Code:
Random r = new Random();
double avg = 10;
Particle a = new Particle(xpos,ypos, r.nextGaussian()+avg,r.nextGaussian()+avg);

Where particle takes in 4 doubles: xpos,ypos,xvel,yvel.

Anyways I'm worried about the way java stores the variables. I'm worried that my particle class will store the addr to r.nextGaussian rather than just a number. This would be bad since then everytime I would call the xvel or yvel the number would change.

Is that assessment correct and does anyone know of a way to fix it if this is correct?

You could specify a variable on the stack and just assign r.nextGaussian() to that variable.

Typically when you want to force a register or some word to take the value instead of the address the function has to pass the arguments BYVAL (by value) instead of BYREF (by reference).

In BASIC languages you use BYVAL or BYREF. In C/C++ you simply use the variable (eg int value) or you use the reference symbol (int &value) for passing the address. I'm not sure what you do in java but theres probably something like the syntax in C++ and if i recall correctly Java doesn't allow you to use pointers which lends me to think that there is definitely a reference syntax thing in there somewhere (I haven't used Java in over 5 years)

chiro