Passing Object to Method in JavaJava 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.
ObjectPassing.java Output: ob1 == ob2: true ob1 == ob3: false Defining A Constructor That Takes an Object of Its Class as A ParameterOne 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 ObjectsIn 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.ConclusionPassing 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.
Next TopicPattern Matching for Switch in Java 21
|