~Gaurav<br />SCJP5
Thanks and Regards
~Gaurav<br />SCJP5
Since the compiler makes a copy of the reference variable before the finally block is executed.Originally posted by Gaurav Bhatia:
I am setting the String reference to point to a new value. Then why is it returning the old value.
Originally posted by Gaurav Bhatia:
Please check the sample code written below :
public class ReturnExample
{
private String normalExecution()
{
String result = "";
try
{
result = "Entered try block.";
return result;
}
catch(Exception e)
{
result = result + "Entered Catch block.";
return result;
}
finally
{
result = result + "Entered finally block.";
}
}
public static void main(String[] args)
{
ReturnExample example = new ReturnExample();
String result = example.normalExecution();
System.out.println(result);
}
}
Why is the result of the program being printed as �Entered try block�.
Although finally block gets executed but the returned value from the function call only contains the string value set in the try block and doesn�t includes the changes done in finally block.
Thanks!!
Sandeep Atluri
Originally posted by sandeep atluri:
if we had placed the return statement in the try block, instead in the finally block.. we would have got the result...
"Entering try Block"
"Entering Finally Block."
understand....
Coming soon... www.javatales.com
~Gaurav<br />SCJP5
~Gaurav<br />SCJP5
Gaurav Bhatia wrote:Alexsandra, it works as expected when using StringBuffer variable.(as you mentioned).
Also, by returning a user defined class's instance/object, the changes done in finally are reflected back in main method (even if return statement is placed in try block).(attached code shows the usage)
public class ReturnExample1
{
private Data normalExecution()
{
Data result = new Data();
try
{
result.setValue(10);
return result;
}
catch(Exception e)
{
result.setValue(20);
return result;
}
finally
{
result.setValue(30);
}
}
public static void main(String[] args)
{
ReturnExample1 example = new ReturnExample1 ();
Data result = example.normalExecution();
System.out.println(result.getValue());
//Value returned is 30.
}
}
class Data
{
int variable = 0;
public void setValue(int i)
{
variable = i;
}
public int getValue()
{
return variable;
}
}
I tried using an int variable, it also gives the same result as with String.
So, the behaviour is different in case of Strings and primitive types.
We begin by testing your absorbancy by exposing you to this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
|