Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

In Java, the method of passing data to functions (also known as methods in Java) can be understood as either "pass-by-value" or "pass-by-reference."

Pass-by-Value

In Java, primitive data types like int, float, double, char, etc., are passed by value. This means that a copy of the actual value is passed to the method, and any change made to that value within the method does not affect the original value outside of the method.

void modifyValue(int x) {
    x = x * 2;
    System.out.println("Value inside method: " + x);
}

public static void main(String[] args) {
    int a = 5;
    modifyValue(a);
    System.out.println("Value outside method: " + a);
}

In this example, the output will be:

Value inside method: 10
Value outside method: 5

The value of a remains unchanged outside the method, indicating that the variable was passed by value.

Pass-by-Reference (kind of)

In contrast, objects of classes (like arrays, instances of user-defined classes, etc.) are also passed by value, but the value that gets passed is the reference to the object, not the actual object itself. This is sometimes confusingly referred to as "pass-by-reference," but it's more accurate to say the object references are passed by value.

Here's an example:

void modifyArray(int[] arr) {
    arr[0] = 99;
    System.out.println("Array inside method: " + Arrays.toString(arr));
}

public static void main(String[] args) {
    int[] myArray = {1, 2, 3};
    modifyArray(myArray);
    System.out.println("Array outside method: " + Arrays.toString(myArray));
}

The output will be:

Array inside method: [99, 2, 3]
Array outside method: [99, 2, 3]

The array is modified inside the method and the change reflects outside the method as well. This happens because the reference to the array is passed by value.

In summary, Java is "pass-by-value" in the sense that it passes a copy of the variable to methods. For primitive types, it's the actual value; for objects, it's the reference to the object. Changes to the object that the reference points to will be visible outside the method, but if you change the reference itself to point to a new object, that change won't be visible outside the method.

  • No labels