public class FinalDemo {
public static void main(String[] args) {
String initialStr = "ANonsenseStr";
for (int i = 0; i < 10; i++) {
// When some condition is met
if (i == 7) {
initialStr = initialStr.equals("ANonsenseStr") ? "AMeaningfulStr" : initialStr;
}
// Do something else(Meaning it's not good enough to just break the loop to make sure initialStr is properly assigned)
System.out.println("i = " + i + ", initialStr = " + initialStr);
}
}
}
i = 0, initialStr = ANonsenseStr
i = 1, initialStr = ANonsenseStr
i = 2, initialStr = ANonsenseStr
i = 3, initialStr = ANonsenseStr
i = 4, initialStr = ANonsenseStr
i = 5, initialStr = ANonsenseStr
i = 6, initialStr = ANonsenseStr
i = 7, initialStr = AMeaningfulStr
i = 8, initialStr = AMeaningfulStr
i = 9, initialStr = AMeaningfulStr
Only when a specific condition is satisfied, assign a value to the variable. And the value remains final once it's assigned.
网友评论