I'm trying to make a 2d game in Java.
In the process I soon noticed that many objects needed bounds (x1, x2, y1, y2) and as a consequence many methods thus had parameters (int x1, int x2, int y1, int y2).
So I thought what the heck, why not make an object IntRectangle with attributes x1, x2, y1, y2 (which I set as public for a performance boost), along with a few helpful methods like getWidth(), getHeight(), etc.
At this point my code is much cleaner and I haven't lost much performance since the variables are public.
I soon noticed, unlike passing primitive values into a method, the values of the passed object changed when I changed them in the method.
For instance, with a primitive value
int x = 10;
subtract5(x);
print(x);
void subtract5(int i) {
i -= 5;
}
this line of code would print 10. But with an object...
class XY {
public int X;
public int Y;
}
main {
XY xy = new XY();
xy.X = 5;
xy.Y = 10;
changeX(xy);
print xy.X;
}
changeX(XY xy2) {
xy2.X = 7;
}
It prints 7;
The theory I've developed is that an int is not a pointer to an int, it's an int stored in the register. It is pushed when a method is called and then popped back when returned, unchanged. An object is a reference to an object. The object itself isn't pushed onto the stack, just the pointer.
But I've tired this with strings (that I know are objects) and they behave just like ints in this matter, which confuses me. Perhaps they make a copy out of themselves somehow?
Well, I hope someone can shed some light on this matter and tell me where my reasoning is taking a wrong turn and hopefully give me some advice on how to clean up my code, keep performance, but without making it venerable.