Java – the behavior of the statement returned in catch, and finally

public class J {
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 the integer of return type with StringBuilder, and the output is 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 anyone can explain it in detail What's the difference?

Solution

Just because the integer is immutable, even if the value returned by the method is changed in the method, it is not reflected, and it is reflected in the 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"));
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>