How to pass an object as an argument in Java programming?
We know that the concept of calling a method as pass by value and pass by reference. Java allows us to pass primitive types of data when calling a method that is called as 'a method call by value' or 'passed by value'. In the same manner, we can create an object by passing primitive type of data using constructors.
Java allows us to create an object by passing reference of another object ie. One Object can be passed to another object. This is called as 'call by reference' or 'passed by reference'.
Syntax
<class name> <object name2> ;
<object name2>=<object name1>;
Passing in by reference can be faster than by value, because when you pass an object by reference you are effectively passing just a pointer to the existing object, whereas passing by value makes a full copy of the object on the stack which is more expensive in terms of CPU time and memory.
How to return an object in Java programming?
A primitive type's assigned value is passed to the method when it is passed as an argument. This means that the value is local to the method and any changes made to it by the method will not affect the value of the primitive you passed to the method.
As is common knowledge, a Java reference points to the memory location of an object when it is assigned to one; otherwise, the object is started as null. It is important to keep in mind that the memory location of the assigned object is represented by the value of the reference. Consequently, if we send a reference as an argument to any method, we are actually passing the memory address of the object that is assigned to that specific reference. This technically indicates that our constructed object is located in memory and accessible by the target method. Therefore, if the target method were to access our object and modify any of its properties, we would discover that the value of our original object has changed.
Comments
Post a Comment