This is a program I got from a Java tutorial online. If I give my understanding of it could someone please tell me if I am correct or tell me where I have gone wrong. I am a newbie so all help is greatly appreciated.
1. The class PassObj has two int variables n1 & n2.
2. These as initialised to zero.
3. In Main, there are 2 instances of the class PassObj created. These are obj1 & obj2.
4. The multiply method is called with parameters 5 & 6 passed to it. The multiplication is done and the result is shown in the console.
My main issues are what is the point of:
PassObj(int p1, int p2)
n1 = p1;
n2 = p2;
and does the instantiation PassObj obj1 = new PassObj(5,6); actually pass parameters to the above constructor.
I am not sure what you want exactly. But, i will try to help. PassObj(int p1, int p2) is to allow you to initialize the variables of a PassObj instance.
The instantiation PassObj obj1 = new PassObj(5,6); actually pass parameters to the above constructor - yes, but here parameters are passed by copy.
How to check when things are passed by copy or value? Try the code below.
Thank you for the tutorial name: was it this example?
Lots of people get confused about pass by value and pass by reference, particularly when people write things like “Primitives are passed by value and Reference types are passed by reference” (see for example this link (No 6)). You can see examples of real‑life pass‑by‑value; cats do it naturally (), as you can read in this thread (if you have a week to spare).
Briefly: if you pass anything to a method, you cannot change the original value. If you could, that would be pass‑by‑reference. You can however change the state of a mutable object.