Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of return statement in catch and finally

public class J {

     public Integer method(Integer x) 
        {
            Integer val = x;
            try 
            {

                    return val;
            } 
            finally 
            {
                     val = x + x;
            }
        }
        public static void main(String[] args) 
        {
            J littleFuzzy = new J();
            System.out.println(littleFuzzy.method(new Integer(10)));
        }

}

It will return "10".

Now I just replace Return type Integer to StringBuilder and Output was changed.

public class I {

     public StringBuilder method(StringBuilder x) 
        {
            StringBuilder val = x;
            try 
            {

                    return val;
            } 
            finally 
            {
                     val = x.append("aaa");
            }
        }
        public static void main(String[] args) 
        {
            I littleFuzzy = new I();
            System.out.println(littleFuzzy.method(new StringBuilder("abc")));
        }


}

OutPut is "abcaaa"

So, Anybody can explain me in detail.? what are the differences.?

like image 262
sachin Avatar asked Feb 28 '12 05:02

sachin


Video Answer


1 Answers

Just because integer in immutable so after method returns even if value is changed in method it does not reflect, and does reflect in StringBuilder Object

EDIT:

public class J {
    public String method(String x) {
        String val = x;
        try {
            return val;
        } finally {
            val = x + x;
        }
    }

    public static void main(String[] args) {
        J littleFuzzy = new J();
        System.out.println(littleFuzzy.method("abc"));
    }
}
like image 89
Nirmal- thInk beYond Avatar answered Oct 23 '22 01:10

Nirmal- thInk beYond