What would happen in memory to concat and concat2, will they be garbage collected or will they stay alive for ever since they are using a static variable?
The String in the concat variable will be eligible for garbage collection when this method returns since it will no longer be reachable.
The lifetime of the String in concat2 that is being returned (modulo the compilation error!!) will depend on what the caller does with it.
The + operator will generate a new String. The fact that it contains characters from an existing String that (in this case) is referenced from a static variable makes no difference. The characters are copied into the new String as it is being formed.
what is the best practice for this
There is no "best practice". Read No Best Practices.
Given that there are no garbage collection implications for concatenating static strings, you don't need to do anything.
As a general rule, you can just let the JVM optimize string concatenations as it sees fit. It will probably produce code that is as good as anything you can achieve. Possibly better ... in recent JVMs.
The only situation where it can be helpful to intervene is if you are constructing a large string by looping over some data structure; e.g.
String res = "";
for (String member: someLargeList) {
res = res + " " + member;
}
For this example may be advisable to use a StringBuilder and append calls to build the string. Better still use StringJoiner or equivalent.
But it is NOT advisable to try to optimize string concatenations in general; see above.
concatwill be some time after the method returns. Butconcat2is returned from the method, and so will be kept in memory so long as there are strong references to the object. As for the variables themselves (not the objects the reference), they'll be deleted when the stack frame is (when the method returns).