If I have code like below is it feasible?
String b = "abc";
String c = "def";
for (int i=0;i<100000000;i++){
String a = b + c; // i got a different object , ahhh!
}
How does it affect the system? Can we improve it and how?
Doesn’t that follow String pool concept, since i am creating String without new operator i’m ending with 1 object, in result it was creating 100000000 object(i was wrong) but i didn’t unserstand how (checked with == operator)
for example
final String b = "abc";
final String c = "def";
for (int i=0;i<100000000;i++){
String a = b + c; //same object referred again and again
}
gives same object , i was able to check with == operator
Isn’t that both the example follow String pool concept? Why does if i have final for my String variable varies the outcome of different object or same object .
If
bandcare not markedfinal, the compiler probably assumes that at some point in the code, different strings might be assigned to those variables. As such, when you writea=b+c, the compiler can’t assume anything about the contents ofbandc(they could even come from the user) so it has to concatenate them and produce a brand new string.When they’re
final, the compiler can know for sure thatbis always"abc"andcis always"def", and possibly even infer that(b+c)=="abcdef", and as such put it in a pool or simply do the concatenation before the loop.