Siemens Interview Question
Software Engineer / DevelopersI guess the question is: Why doesn't a swap method works for objects?
Ans: It is because, everything in Java is pass by value. So by swapping objects we are only trying to swap references(assuming object's are passed in the method as parameters), which is not possible in Java. Hence, it doesn't work.
We are passing copy of references as arguments to the method. Method manipulates the copies of references but not original reference.
public class PassByReference
{
public static void main(String args[])
{
String st = new String("hi");
method(st);
System.out.println(st);
}
//here q is another reference to 'hi' object
static void method(String q)
{
System.out.println(q);
q = new String("bye");
}
}
I am not sure I understand your question . Can you be more precise ?
- Anonymous August 06, 2010