For the first call with foo(0), the finally block prints the output value then returns the output value which is then printed by the system.out call in main method.so value 'b' is printed two times.
For second call with foo(1),the catch block make output as 'ba' and returns 'ba' to main method, but before returning finally block is called always...so before printing the returned value i.e. 'ba' first finally block prints the 'bab' value...after that since the return value is 'ba' only thats y main prints 'ba'
so the sequence is
b
b
bab
ba