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);
}
}
Why is this printing hii
after returning from the function go()
, the value has changed to "hello" in the finally block?
the output of the program is
finally value of q is hello
hii
Try using StringBuffer instead of String and you will see the change .... it seems the return statement blocks the object which is to be returned and not the reference. You could also try to verify this by printing the hashcode of :
object being printed from main()
public static void main(String[] args){