Javatpoint Logo
Javatpoint Logo

Passing Object to Method in Java

Java is strictly pass-by-value language. When we pass a primitive type to a method, the method receives a copy of the value. However, when we pass an object to a method, the method receives a reference to the object. When we made changes to the object inside the method will be reflected in the object outside the method.

Basically, a parameter cannot be changed by the function, but the function can ask the parameter to change itself via calling some method within it.

  • While creating a variable of a class type, we only create a reference to an object. Thus, when we pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument.
  • It means that objects act as if they are passed to methods by use of call-by-reference.
  • Changes to the object inside the method do reflect the object used as an argument.

ObjectPassing.java

Output:

ob1 == ob2: true
ob1 == ob3: false

Defining A Constructor That Takes an Object of Its Class as A Parameter

One of the most common uses of object parameters involves constructors. Frequently, in practice, there is a need to construct a new object so that it is initially the same as some existing object. To do this, either we can use Object.clone() method or define a constructor that takes an object of its class as a parameter.

PassingObjectExample.java

Output:

Volume of mybox is 3000.0
Volume of myclone is 3000.0

Returning Objects

In Java, a method can return any type of data, including objects. For example, in the following program, the incrByTen( ) method returns an object in which the value of an (an integer variable) is ten greater than it is in the invoking object.

PassingObject.java

Output:

ob1.a: 2
ob2.a: 12

Note: When an object reference is passed to a method, the reference itself is passed by use of call-by-value. However, the value being passed refers to an object, the copy of that value will still refer to the same object that its corresponding argument does. That's why we said that Java is strictly pass-by-value.

Conclusion

Passing objects to methods is a powerful technique that allows we to share data between different parts of our program. It is also essential for using many of the built-in Java classes and libraries.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA