sac*_*hin 10 java try-catch-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)));
}
}
Run Code Online (Sandbox Code Playgroud)
它将返回"10".
现在我只是将Return type Integer替换为StringBuilder并更改了Output.
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")));
}
}
Run Code Online (Sandbox Code Playgroud)
OutPut是"abcaaa"
所以,任何人都可以详细解释我.有什么区别.?
只是因为immutableso after 方法中的整数返回,即使方法中的值发生更改,它也不会反映,并且会反映在StringBuilderObject中
编辑:
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"));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
260 次 |
| 最近记录: |