In preparation for the SCJP exam (or OCPJP as we now know), some of the mocking questions regarding the meaning of pass-by- (reference) and immutability catch me.
I understand that when you pass a variable to a method, you pass a copy of the bits that represent how to get to that variable, and not from the actual object itself.
The copy you are sending points to the same object, so you can change this object if it is changed, for example, add it to StringBuilder. However, if you are doing something with an immutable object, for example, with the addition of Integer, the local reference variable now points to the new object, and the original reference variable does not pay attention to this.
Consider my example here:
public class PassByValueExperiment
{
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder();
sb.append("hello");
doSomething(sb);
System.out.println(sb);
Integer i = 0;
System.out.println("i before method call : " + i);
doSomethingAgain(i);
System.out.println("i after method call: " + i);
}
private static void doSomethingAgain(Integer localI)
{
localI++;
}
private static void doSomething(StringBuilder localSb)
{
localSb.append(" world");
}
}
. , , ? ?