- Java is always pass by value.
- Primitive data type arguments like int or double are passed into methods by value. Any changes to the value of the parameters is limited to the scope of the method. When method returns any changes are lost.
- When objects are used Java copies and passes the references by value. This is often confused and best explained with examples. In this example below arg1 and arg2 point to the original StringBuilder objects and they hold a reference. In the swap1 function we are actually swapping the reference values between arg1 and arg2 and hence the original contents of the StringBuilder objects in main are not modified. In the swap2 function are actually modifying the content of objects to which arg1 and arg2 point and hence the content of objects in main are modified.
public class PassValueTest { private static void swap1(StringBuilder arg1, StringBuilder arg2) { StringBuilder temp = arg2; arg2 = arg1; arg1 = temp; } private static void swap2(StringBuilder arg1, StringBuilder arg2) { String temp = arg2.toString(); arg2.replace(0, arg2.length(), arg1.toString()); arg1.replace(0, temp.length(), temp); } public static void main(String[] args) { StringBuilder str1 = new StringBuilder("Hello"); StringBuilder str2 = new StringBuilder("World"); System.out.println("Before swap = " + str1 + " " + str2); swap1(str1, str2); System.out.println("After swap1 = " + str1 + " " + str2); swap2(str1, str2); System.out.println("After swap2 = " + str1 + " " + str2); } }This example produces the following output.
Before swap = Hello World After swap1 = Hello World After swap2 = World Hello
0 comments:
Post a Comment