Return to site

☕🎓JAVA CERTIFICATION QUESTION: pass by value

· ocp,java

Given:

What is the output?

* abc

* ABC

* An exception is thrown.

* Compilation fails.

#java #certificationquestion #ocp

The output of the given code is abc.

Let's break down why this is the case:

Step-by-Step Explanation:

List Initialization:

List abc = List.of("a", "b", "c");

abc is a reference to an immutable list containing the strings "a", "b", and "c".

 

First Stream with forEach:

abc.stream()

.forEach(x -> {

x = x.toUpperCase();

});

This code creates a stream from the list and iterates over each element with forEach.

Within the lambda expression x -> { x = x.toUpperCase(); }, x is a new local variable that holds the reference value of each element of the list.

When x = x.toUpperCase(); is executed, it changes the local variable x to point to a new string object that is the uppercase version of the original string (e.g., "a" becomes "A").

However, this reassignment does not affect the original list because x is a local variable within the lambda.

The reference held by the list itself remains unchanged.

Here's a visualization:

For the first element "a":

x initially holds the reference to "a".

x = x.toUpperCase(); makes x hold the reference to "A".

The list still holds the reference to "a".

The same process repeats for "b" and "c".

 

Second Stream with forEach:

abc.stream()

.forEach( System.out::print);

This creates another stream from the list and iterates over each element with forEach.

It prints each element of the list.

Since the elements of the list were not modified by the previous forEach operation (because only the local variable x was changed, not the elements in the list), the second forEach prints the original elements of the list: "a", "b", "c".

 

Key Points:

Pass by Value: Java passes the value of the reference to the lambda.

This means x is a new variable within the lambda that holds the reference to the original string.

Local Variable Reassignment:

When x = x.toUpperCase(); is executed, it only changes the local variable x to point to a new string.

It does not modify the original list because x is a local variable within the lambda expression.

Immutable List: The list created with List.of(...) is immutable, so its elements cannot be modified directly.

 

Conclusion:

Because the original list elements are not modified, the output of the code is:

abc

This aligns with the understanding that Java uses pass by value, creating new variables in the lambda that hold the reference values, but does not alter the original references held by the list.