JavaChallenge39
1. true
2. false
3. Ambiguitious
4. Compilation Error
Try to solve the challenge by yourself first.
We know that finally
block always gets executed unless you are not exiting from the code. So, the answer will be false
. But how the compiler will make sure that the return statement of the try block is not running instead finally block one will execute. Let’s see the byte-code —
public class JavaChallenge39 {
public JavaChallenge39() {
}
public static void main(String[] args) {
System.out.println(ret());
}
public static boolean ret() {
try {
boolean var0 = true;
return false;
} finally {
;
}
}
}
At the compile-time, the compiler is smartly converting the code into byte code which will help the JVM to execute the code without any ambiguity. Here, return false;
will be executed but still the finally block will also be executed and it has empty body so it will not do anything. Let’s try some other code —
public class JavaChallenge39 {
public static void main(String[] args) {
System.out.println(ret());
}
public static Boolean ret(){
try {
throw new RuntimeException();
} finally {
return true;
}
}
}
The compiled code(byte-code) —
public class JavaChallenge39 {
public JavaChallenge39() {
}
public static void main(String[] args) {
System.out.println(ret());
}
public static Boolean ret() {
try {
throw new RuntimeException();
} finally {
return true;
}
}
}
Here the compiler will not be able to do any optimization and the JVM will run the code as normal. Try couple of more combinations such as —
1. Change Boolean to boolean
2. return false instead of true in finally block
You understanding will be more clear.