I have the following Java class:
public class Test {
public static void main(String[] args) {
if (false) {
log("String_to_be_never_printed_1");
}
if (isPrintable()) {
log("String_to_be_never_printed_2");
}
}
private static boolean isPrintable() {
return false;
}
private static void log(String s) {
System.out.println(s);
}
}
In both if statements, the result will be false. When I output the constant pool table for this class, I get:
Constant pool:
#1 = Class #2 // Test
#2 = Utf8 Test
....
#18 = Utf8 isPrintable
#19 = Utf8 ()Z
#20 = String #21 // String_to_be_never_printed_2
#21 = Utf8 String_to_be_never_printed_2
#22 = Methodref #1.#23 // Test.log:(Ljava/lang/String;)V
#23 = NameAndType #24:#25 // log:(Ljava/lang/String;)V
...
The String_to_be_never_printed_2 is present (#20), when String_to_be_never_printed_1 is nowhere to be seen. This is expected as the compiler optimized the first if statement.
My question is whether the VM will manage to remove the String_to_be_never_printed_2 from the constant pool (as this will never be used)?
Nothing is ever removed from the constants pool. There would be no purpose in this anyway, as removal would have no effect on actual memory size