Passing Variables to Method (PVM)


PVM:   SOLD       




In our example, we have tried to pass a variable to a method. However, we cannot distinguish between the different types of variable passing in Java. There are two types of data passing to a method, the first is pass-by-value and the second is pass-by-reference.

1. Pass-by-Value

When pass-by-values ​​occurs, the method uses a copy of the value of the variable passed to the method. The method cannot be directly modified by its arguments, even if its parameters are modified during the calculation.


Pass-by-Value Example

In the above example given, we call the test method and pass the value of i as a parameter. The value of i is copied to the variable j in the method. Since j is a replacement variable in the test method, it will not affect the value of the variable if i in main since it has a different copy of the variable.

By default, all primitive data types when passed to a method are pass-by-values.

2. Pass-by-reference

When a pass-by-reference occurs, a reference to an object is passed by calling a method. This means that the method copies the reference to the variable that is passed to the method. However, unlike pass-by-value, the method can create the actual object that the method is pointing to, since, despite the different descriptors used in the method, the location of the data they point to is the same.


Pass-by-reference Example


Example 2 Pass-by-reference

3. Program Writing Instructions

The wrong situation about value by reference in java is when making swap method using Java reference, note about Java object manipulation 'by reference' but object value of reference from method 'by value,'" is the result, you can't write standard swap method to swap object.


Post a Comment

Previous Next

نموذج الاتصال