I am well aware that Java passes parameters by value, and how that since objects are kept in varaibles as references it is possible to change object values when those values are mutable. What I also understand is that class String contains objects that are immutable. So, to test my understand I decided to write a bit of code that would pass an object to a method as a parameter, change both its string and int variables, and then print it. I expected that, since the parameter is merely a copy, these changes would not affect the variable passed in. Does passing in an object as a parameter not copy the entire object into a new variable an simply passes that objects reference? This is counter to what I have been told by several sources. Here is the code in question:
public class Test {
public int testVar = 20;
public String testString = "Hello";
public static void testCheck(Test test){
test.testString = new String("GoodBye");
test.testVar = 10;
}
public void printTest(){
System.out.println("testVar: " + testVar + " testString: " + testString);
}
public static void main(String[] args) {
Test test1 = new Test();
test1.printTest();
testCheck(test1);
test1.printTest();
}
}
Output:
testVar: 20 testString: Hello
testVar: 10 testString: GoodBye
Expected:
testVar: 20 testString: Hello
testVar: 20 testString: Hello
Thanks in advance.