I'm working on a Java question for my school which gives me this utility class:
import java.util.*;
public class PassByValue
{
private PassByValue() {}
public static void add(int a)
{
a = a + 1;
}
public static void add(Set<String> b)
{
b = new HashSet<String>();
b.add("ABC");
}
public static void add(List<Integer> c)
{
c.add(new Integer(1));
}
}
It also gives me this class with the main method
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PassByValueClient
{
public static void main(String[] args)
{
PrintStream output = System.out;
int a = 1;
PassByValue.add(a);
output.println(a);
Set<String> b = new HashSet<String>();
PassByValue.add(b);
output.println(b.size());
List<Integer> c = new ArrayList<Integer>();
PassByValue.add(c);
output.println(c.size());
}
}
We are supposed to predict the output. When I predicted what the output would be, my guess was 1
, 0
, and 0
respectively. However, when I ran the code the output I got was 1
, 0
, and 1
respectively. From what I understand about passing parameters/arguments into methods, the client's code should remain unchanged. Can someone tell me why the output is 1
instead of 0
?