Consider line 2 and line 3 in the following code.....
class ModifyObjects {
static void modifyString1(String s){
s = "xyz";
//Or any other operations
}
static String modifyString2(String s){
s = "xyz";
return s;
//Or any other operations
}
static void modifyPrimitive1(int i){
i=9;
}
static int modifyPrimitive2(int i){
i=9;
return i;
}
}
public class Operations {
public static void main(String[] args) {
// TODO Auto-generated method stub
String st1 = "abcd";
String st2 = "qwerty";
String st3;
int i1=0, i2;
st1 = "xyz"; //line 1
System.out.println("st1: " + st1);
ModifyObjects.modifyString1(st2);
System.out.println("st2: " + st2); //line 2
st3 = ModifyObjects.modifyString2(st2);
System.out.println("st3: " + st3);
System.out.println("st2: " + st2);
ModifyObjects.modifyPrimitive1(i1);
System.out.println("i1: " + i1); //line 3
i2 = ModifyObjects.modifyPrimitive2(i1);
System.out.println("i2: " + i2);
}
}
line 2 gives st2 as qwerty (does not modify. Should be xyz.) line 3 gives i1 = 0 (does not modify. Should be 9.)
This looks a bit odd. Here is the ouput:
st1: xyz
st2: qwerty
st3: xyz
st2: qwerty
i1: 0
i2: 9
Also at line 1 a new string object "xyz" is created right? I think "abcd" is just not being referenced from here.