Function Calls:
In Java, there are two ways to pass arguments to a method: call by value and call by reference.
Call by value means that a copy of the value of the argument is passed to the method, and any changes made to the argument within the method do not affect the original value of the argument.
Here’s an example of a method that uses call by value:
public static void increment(int x) {
x++;
}
int num = 5;
increment(num);
System.out.println(num); // Output: 5
In this example, the increment() method takes an integer argument x and increments it by 1. However, when the increment() method is called with the argument num, which has a value of 5, the value of num remains unchanged after the method call. This is because the method operates on a copy of num, not the original variable.
Call by reference, on the other hand, means that the memory address of the argument is passed to the method, and any changes made to the argument within the method affect the original value of the argument.
Here’s an example of a method that uses call by reference:
public static void append(StringBuilder sb) {
sb.append(" World");
}
StringBuilder sb = new StringBuilder("Hello");
append(sb);
System.out.println(sb.toString()); // Output: "Hello World"
In this example, the append() method takes a StringBuilder argument sb and appends the string ” World” to it. When the append() method is called with the argument sb, which has a reference to a StringBuilder object containing the string “Hello”, the original object is modified to contain the string “Hello World”.
Note that in Java, call by reference is actually implemented as call by value of the reference. This means that the memory address of the object is passed by value to the method, but since the reference points to the same object in memory, any changes made to the object within the method affect the original object outside the method.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.