I've written seven test cases for understanding the behavior of finally block. Can you guys explain the logic behind how finally works??
package core;
public class Test {
public static void main(String[] args) {
new Test().testFinally();
}
public void testFinally() {
System.out.println("One = " + tryOne());
System.out.println("Two = " + tryTwo());
System.out.println("Three = " + tryThree());
System.out.println("Four = " + tryFour());
System.out.println("Five = " + tryFive());
System.out.println("Six = " + trySix());
System.out.println("Seven = " + trySeven());
}
protected StringBuilder tryOne() {
StringBuilder builder = new StringBuilder();
try {
builder.append("Cool");
return builder.append("Return");
} finally {
builder = null;
}
}
protected String tryTwo() {
String builder = "Cool";
try {
return builder += "Return";
} finally {
builder = null;
}
}
protected int tryThree() {
int builder = 99;
try {
return builder += 1;
} finally {
builder = 0;
}
}
protected StringBuilder tryFour() {
StringBuilder builder = new StringBuilder();
try {
builder.append("Cool");
return builder.append("Return");
} finally {
builder.append("+1");
}
}
protected int tryFive() {
int count = 0;
try {
count = 99;
} finally {
count++;
}
return count;
}
protected int trySix() {
int count = 0;
try {
count = 99;
} finally {
count = 1;
}
return count;
}
protected int trySeven() {
int count = 0;
try {
count = 99;
return count;
} finally {
count++;
}
}
}
Why builder = null
is not working?
Why builder.append("+1")
works where as count++
( in trySeven()) does NOT work?