Well, what I found is as follows,
Return actually returns a value and its gets copied to String a=obj.go();
, before execution goes to Finally.
Lets verify it by following experiments.
public class Test2 {
public static void main(String[] args) {
Test2 obj=new Test2();
String a=obj.go();
System.out.print(a);
}
public String go() {
String q="hii";
try {
return q;
}
finally {
q="hello";
System.out.println("finally value of q is "+q);
}
}
the output of the program is
finally value of q is hello
hii
and if we take StringBuffer instead of String as follows,
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test2 obj=new Test2();
StringBuffer a=obj.go();
System.out.print(a);
}
public StringBuffer go(){
StringBuffer q=new StringBuffer("hii");
try{
return q;
}
finally{
q.replace(0, q.length(), "hello");
System.out.println("finally value of q is "+q);
/*return q1;*/
}
}
}
The output comesout to be,
finally value of q is hello
hello
and finally if we take int instead of String as follows,
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test2 obj=new Test2();
int a=obj.go();
System.out.print(a);
}
public int go(){
int q=1;
try{
return q;
}
finally{
q=2;
System.out.println("finally value of q is "+q);
/*return q1;*/
}
}
}
the output is
finally value of q is 2
1
**Ananlysis**
1.In first case, return copied adress of String in variable a, then excecution goes to Finally where String is changed. But since in case of Strings, we can't manipulate any String a new String is constructed. So in variable a address of original string is saved, which gets printed.
2.In second case, return copied address of StringBuffer in variable a, and in finally this StringBuffer object is manipulated, rather creating new one. so the value which was stored in variable a also gets manipulated, that's seen in print statement.
3.In third case, value of int is copied in variable a, before execution goes to finally. and thus a gets value of 1. and then in finally we changed value of q which doesn't anyway change value of a.